So I was looking for ways to call a child component method from parent component without using refs to child and found an interesting solution.
var Child = {
template: '<div>{{value}}</div>',
data: function () {
return {
value: 0
};
},
methods: {
setValue(value) {
this.value = value;
}
},
created() {
this.$emit('handler', this.setValue);
}
}
new Vue({
el: '#app',
components: {
'my-component': Child
},
methods: {
setValueHandler(fn) {
this.setter = fn
},
click() {
this.setter(70)
}
}
})
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script>
<div id="app">
<my-component @handler="setValueHandler"></my-component>
<button @click="click">Click</button>
</div>
As you can see this is a simple VueJS application where the OP is emitting a handler function from child to parent, so that when the parent calls this handler it updates the child state. However, I have a hard time understanding why this happens. In the solution above the child method setValue sets this.value, however when we call the emitted method in parent component shouldn't the parent look for the "value" field in parent scope, and not update "value" from child scope.
I didn't get a response from the OP, since this is an old post that I referred to. So would appreciate anyone who can help me understand this.