0đź‘Ť
âś…
Calling child component’s method from parent component
Say you have a child-comp
component and want to call its childMethod
method from the parent.
Use ref="someVariableName"
on the parent’s template and this.$refs.someVariableName
on the parent’s JavaScript.
Parent’s template:
<div id="app>
<child-comp ref="myChild"></child-comp>
<button @click="callChildMethod">GO</button>
</div>
Parent’s JavaScript code:
{
data: // ...
// ...
methods: {
callChildMethod: function () {
this.$refs.myChild.childMethod();
}
}
Calling parent’s method from child
Emit an event in <child-comp>
and listen to it in parent.
Parent’s template (listening to an event):
<div id="app>
<child-comp @eventname="parentsMethod"></child-comp>
</div>
Notice that @eventname="parentsMethod"
is the same as v-on:eventname="parentsMethod"
.
Parent’s JavaScript code:
{
data: // ...
// ...
methods: {
parentsMethod: function (event) {
console.log('parent called', event);
}
}
Child’s JavaScript code:
{
data: // ...
// ...
methods: {
someChildMethod: function () {
this.$emit('eventname', {some: 'object value'});
}
}
Now whenever, at the child, you call someChildMethod
it will trigger the event and, since the parent is listening to it, it will execute parentsMethod
in the parent.
👤acdcjunior
Source:stackexchange.com