E
E
Eugene2019-10-30 14:30:34
Vue.js
Eugene, 2019-10-30 14:30:34

How to listen to child component events in Vue js?

Hello.
Can you please tell me how to listen to the events of the child component and change the data in the parent component depending on the value received?
The parent component has a variable isShow: false
In the child component, you need to listen for changes in the parentIsShow variable and assign it to the parent variable if there were changes.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
dicem, 2019-10-30
@djon_pulse

I'll give you an example. For example, you have a parent component: Page.vue it has a button that opens the Modal.vue modal window.
Page.vue:

<button @click="isShow = !isShow">Open Modal</ button>

<Modal v-if="isShow" @closeModal="isShow = !isShow"/>

When clicked, we open a modal window.
Meanwhile, inside the component itself, we need to be able to close it, in which case we write in the child component Modal.vue:
...
<button @click="$emit('closeModal')">Close Modal</button>
...

To pass data, use $emit like this:
$emit('closeModal', {
  data: 'value',
  data2: 'value2'
})

You can read more here: https://medium.com/@modex13/vue-js-2-data-transfer...
Here it is written more simply: https://monsterlessons.com/project/lessons/peredae...
Also you can use the following (but remember that this is an edge case and is not recommended for use): https://ru.vuejs.org/v2/guide/components-edge-case...

E
Eugene, 2019-11-01
@djon_pulse

Thanks for the comments, they gave me the right idea.
In the parent component, in the call to the child component, specified

methods: {
   // Изменить переменную в родительском компоненте на значение переменной в дочернем компоненте
   function() {
       this.isShow = this.$refs.childComponent.parentIsShow;
   }
}

In child component:
methods: {
   clickButtonInChildComponent() {
       this.parentIsShow = terue;
       this.$emit('emitChildComponent', this.parentIsShow);
   }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question