Vue学习:全局事件总线2-可以实现任意组件间的通信-实现x组件上存在$on,$off,$emit方法

已知$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');//销毁
        },

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值