console
Vue.component('parent-component',{
template: `
<div>
{{ title }}
<br/>
<child-component @updateParent="update">
</child-component>
</div>
`,
data(){
return {
title: "父组件"
}
},
methods: {
update(){
this.title = "父组件更新了";
},
},
created(){
this.$on("updateParent",()=>{
console.log('这里不会执行');
});
}
});
Vue.component('child-component',{
template: `
<div>
{{ title }}
<br/>
<button @click="updateByEmit">
通过 $emit 更新父组件
</button>
</div>
`,
data(){
return {
title: "子组件"
}
},
methods: {
updateByEmit(){
this.$emit("updateParent");
},
},
created(){
this.$on("updateParent",()=>{
this.title = "子组件也更新了"
});
}
});
new Vue({
el: '#root',
})
<script src="https://unpkg.com/vue"></script>
<div id="root">
<parent-component>
</parent-component>
</div>