全局事件总线(GlobalEventBus)

全局事件总线(GlobalEventBus)

使用步骤: 1.main.js定义“全局事件总线” 2.在A组件想接收数据 3.在B组件想发送数据

1.main.js定义“全局事件总线”

//创建vm
new Vue({
    el:'#app',
    render: h => h(App),
    beforeCreate() {
        Vue.prototype.$bus = this
    }
})
​
2.在A组件想接收数据,定义this.$bus.$on和this.$bus.$off
​
mounted() {
    // console.log('School',this)
        this.$bus.$on('hello',(data)=>{
            console.log('我是School组件,收到了数据',data)
        })
    },
    beforeDestroy() {
        this.$bus.$off('hello')
    }
​

3.在B组件想发送数据,定义this.$bus.$emit

methods: {
    sendStudentName(){
        this.$bus.$emit('hello',this.name)
    }
}

注意点1:

问题:“全局事件总线”需要哪些特点?

答案: 1)被所有组件(vc、vm)能够看得见 2)能够调用$on、$emit、$off

注意点2:

问题:Vue原型对象上面的所有属性和方法是给谁用的?

答案:是给所有的vm和vc使用的

注意点3ÿ

你可能感兴趣的:(前端,javascript,vue.js,前端)