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)
}