I seem to recall being able to emit an event from a parent component to a child component by specifying the emitted event in the opening <template>
tag of the corresponding child component. However for some reason it is no longer working in my implementation. Am I delusional or was this possibly a feature from an older version of VueJS
that was deprecated, possibly in place of the event bus architecture? I am currently using Vue v2.6.12
.
In my $root vue instance:
var app = new Vue({
el: '#app',
router,
data: () => ({}),
methods: {
clearForm() {
this.$emit('clear-form');
}
}
});
Laravel layout:
<v-main>
@yield('content')
</v-main>
Vue Router /Laravel view/vue:
@extends('layouts.user')
@section('content')
<transition name="slide">
<router-view></router-view>
</transition>
@endsection
When clearForm()
is called in the $root instance, shouldn't I be able to capture the emitted event in a child component like this...
<template @clear-form="clearForm"></template>
<script>
export default {
data() {
},
created() {
this.$on('clearForm', clearForm);
},
methods: {
clearForm() {
//this is the method i want to call when emitted from $root
}
}
}
</script>
UPDATE:
The answer I selected from @JoshuaAngnoe is the correct method of passing an emitted event from a $root Vue instance
to a child component served through Vue-Router
. However in my case, I was also leveraging the Laravel
framework, which adds an additional layer of complexity because the HTML is broken up into two files (layout & view).
The Laravel
View, which houses the <router-view>
element, is separate from the Laravel
layout which is actually the same layer as the $root Vue instance. So an additional step is required to make it work...
The declaration for the emitted event, which in the chosen answer, resides within the <router-view>
element: <router-view @clear-form="clearForm" />
needs to be moved out of the <router-view>
element, and into the opening template tag of the child component: <template @clear-form="clearForm">
.
The structure of my initial example was correct. I was just missing $root
when I called $on
to capture the emitted event from the child component.
created() {
this.$on('clearForm', clearForm);
}
Needed to be:
created() {
this.$root.$on('clearForm', clearForm);
}
<ChildComponent :function="myFunction" />
like this then parentmyFunction
function will bind to childfunction
this function – Kamlesh Paul<ChildComponent :method="parentMethod" />
like this – Kamlesh Paul<ChildComponent :method="parentMethod" />
– McWayWeb