I'm trying to figure out how to get a child component to communicate with the parent component, without having a hard binding between them.
From what I've read, custom events should be the thing. But I can't get the parent component to receive and act on the event.
In my sample below I expect clicking on the "Do stuff" button in <child>
to trigger doStuff()
in <parent>
. I see the log message that indicates the button was clicked, but I see no log message indicating that the emitted message was ever received by the parent.
Sample HTML:
<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
</head>
<body>
<div id="app">
<parent>
<child></child>
</parent>
</div>
</body>
</html>
Sample Javascript:
Vue.component('parent', {
props: [],
template: `
<div v-on:stuff="doStuff">
<h1>Hello World (from parent)!</h1>
<slot></slot>
</div>
`,
methods: {
doStuff: function() {
console.log('Do stuff');
}
}
});
Vue.component('child', {
props: [],
template: `
<div>
Hello World (from child)!<br>
<button v-on:click="performClick">Do stuff</button>
</div>
`,
methods: {
performClick: function() {
console.log('Do something');
this.$emit('stuff');
}
}
});
var app = new Vue({
el: '#app',
})