已知$on,$off,$emit方法在vm,vc的原型对象上
所以可以构造一个实例对象,等于x
const Demo=Vue.extend({})//返回值是构造函数
const d=new Demo() //是实例对象vc
Vue.prototype.x=d
并且可以实现传递:实现学生发给学校数据
学生触发
methods: {
sendStudentNameToSchool(){
//触发x的方法 回调在学校里面
this.x.$emit('send',this.name)
}
},
回调在学校
mounted() {
//console.log(this.x)
this.x.$on('send',(data)=>{
console.log('school组件,收到了数据:',data)
})
},
标准:安装全局事件总线 x
new Vue({
el: '#app',
render: h => h(App),
beforeCreate(){//带数据代理没有完成
Vue.prototype.x=this
}
});
但是一般为$bus:总线---其他的都能看到 $为了迎合设计
new Vue({
el: '#app',
render: h => h(App),
beforeCreate(){//带数据代理没有完成
Vue.prototype.$bus=this
}
});
在总线上 你绑定了之后要销毁最好
mounted() {
//console.log(this.x)
this.$bus.$on('send',(data)=>{
console.log('school组件,收到了数据:',data)
})
},
beforeDestroy() {
this.$bus.$off('send');//销毁
},