Home > Mobile >  Vue Component control Component instance variable by another same Component
Vue Component control Component instance variable by another same Component

Time:03-30

So here I have a situation actually i am creating a popup on menu item. and popup is a component. So what i wanna achieve is to change the variable isOpen to false when another instance of component itself is called. let say for example

if menu item 1 is clicked popup component opens ( isOpen = true ) if menu item 2 is clicked popup component opens ( isOpen = true )

so this time there are two same component opens here if first one is clicked, second component should be automatically closed. but i can't figure it out that how can i change the popup.vue(component) variable isOpen is second popup component is clicked.

The issue is attached in the Sanbox Demo have a look. Sandbox Link

CodePudding user response:

The main issue is your state is stored in the popups instead of the component that holds the popups

For example:

<popup v-model='pop1' />
<popup v-model='pop2' />

watch(pop1, value => {
 if (value) pop2 = false
})

With that said, you can workaround by having your popups emit an open event. When the parent receives this, it can close the other popup.

<popup ref='pop1' @open='$refs.pop2.close()' />
<popup ref='pop2' />

With many menus, it will be best to have a currentMenu property you set. When a new menu opens, you update the current member.

<popup ref='pop1' :value='current==="p1"' @open='current="p1"' />
<popup ref='pop2' :value='current==="p2"' @open='current="p2"' />
  • Related