核心:
- 在vue原型中挂载vue实例
- 通过this.bus.$emit('事件名', '参数')向外触发事件和传递参数
- 在生命周期函数mounted中,通过this.bus.$on('传递出来的事件名, callback')来做后续逻辑处理
Demo(实现点击,使得另外一个也改变成自己的名字)
<div id="app">
<child content="吴旭飞"></child>
<child content="左晶晶"></child>
</div>
<script>
Vue.prototype.bus = new Vue() // 在vue原型中挂载vue实例
Vue.component('child', {
data () {
return {
selfcontent: this.content
}
},
props: {
content: {
type: String,
}
},
template: '<div @click="handleClick">{{selfcontent}}</div>',
methods: {
handleClick () {
this.bus.$emit('change', this.selfcontent) // 通过this.bus.$emit('事件名', '参数')向外触发事件和传递参数
}
},
mounted() { // 3. 在生命周期函数mounted中,通过this.bus.$on('传递出来的事件名, callback')来做后续逻辑处理
this.bus.$on('change', data => {
this.selfcontent = data
})
},
})
var app = new Vue ({
el: '#app'
})
</script>
复制代码