vue emit
by kordarei
HTML
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id="app">
<first-component></first-component> <br>
<second-component></second-component>
</div>
</body>
</html>
JavaScript
const FirstComponent = {
template: '<div >{{ name }}</div>',
data() {
return {
name: ''
}
},
methods: {
updateName(name) {
this.name = name
}
},
mounted() {
this.$root.$on('updateName', (name) => this.updateName(name))
}
}
const SecondComponent = {
template: `<input @input="$root.$emit('updateName', $event.target.value)"></input>`,
}
new Vue({
el: '#app',
components: {
FirstComponent,
SecondComponent
}
})