一、main.js给Vue原型对象
new Vue({
//app放入容器中
el:'#app',
//创建元素
render: h => h(App),
beforeCreate() {
Vue.prototype.$bus = this
}
})
二、组件发送数据
<button @click="sendUserName">发送用户数据</button>
sendUserName(){
this.$bus.$emit('test',this.userList)
},
三、接收数据
mounted() {
this.$bus.$on('test',(users)=>{
console.log(users)
})
},
四、销毁
beforeDestroy() {
this.$bus.$off('test')
},
参数介绍: 1、main.js 中的this 其实就是new Vue() 对象, 原理其实是通过vm实现各组件间的通信
2 、 $emit() 第一个参数是参数名称 要对应好,不要重复了
3、 $off解绑事件