【插件】组件通信 Vue-bus

vue-bus.js

export default function install(Vue){
    const Bus = new Vue({
        methods:{
            emit(event, ...args) {
                this.$emit(event, ...args)
            },
            on(event,callback) {
                this.$on(event,callback)
            },
            off(event,callback) {
                this.$off(event,callback)
            }
        }
    })
    Vue.prototype.$bus = Bus
}

main.js

import VueBus from './vue-bus'
Vue.use(VueBus)

Father.vue

created() {
    this.$bus.on('add', this.change)
}
beforeDestroy() {
    this.$bus.off('add', this.change)
},
methods:{
    change(num) {
        this.number = num
    }
}

Son.vue

<button @click="change"></button>
change() {
    this.$bus.emit('add', 1)
}

 

上一篇:错误 LNK2005 “class std::vector<class Bus,class std::allocator > bus” (?bus@@3V?vector@VBus@@V?vector@


下一篇:vue-Vue中的组件传值