- 全局事件总线:
new Vue({
render: h => h(App),
beforeCreate(){
Vue.prototype.$bus=this
}
}).$mount('#app')
methods:{
handleLink(){
this.$bus.$emit('hello',666)
}
}
mounted() {
this.$bus.$on("hello", (data) => {
console.log("我接受到school组件的传值" + data);
});
},
beforeDestroy() {
this.$bus.$off("hello");
},
- 消息订阅与发布(pubsub-js )
npm i pubsub-js
import pubsub from 'pubsub-js'
this.pubId=pubsub.subcribe('事件名',(a,b)=>{
console.log(b)
})
pubsub.publish('事件名',传递参数)
beforeDestroy() {
this.$bus.$off("hello");
pubsub.unsubscribe(this.pubId)
},