vue2笔记7 自定义事件,全局事件总线,消息发布订阅

自定义事件

自定义组件触发事件

vc.$emit(‘my-event’,…params)

绑定自定义组件事件

  • 如需绑定自定义组件的原生事件,需要加上.native修饰符,否则将作为自定义实现处理
  • 如果绑定自定义组件的原生事件,其实是绑定了自定义组件最外层元素的对应原生事件
<template>
<MyComp ref="myComp" 
	v-on:my-event="alert('on my-event!')" 
	@click.native="alert('on click!')"
/>
</template>
<script>
export default {
	mounted() {
		let vc = this
		this.$ref.myComp.$on('my-event',function() {
			// 注:此处this指向myComp
		})		
		this.$ref.myComp.$on('my-event',() => {
			// 注:此处this指向vc
		})		
	}
}
</script>

全局事件总线

使用一个对象作为总线,集中接收其他组件对象发布的事件,所有组件都可以通过总线对象订阅对应事件

const vm = new Vue({
    render: h => h(App),
    beforeCreate() {
    	// 此钩子执行时还未解析模板,此时在Vue原型中注册$bus,即可在所有组件中通过this.$bus获取到vm
        Vue.prototype.$bus = this
    }
}).$mount('#app')

注:最好在订阅了全局事件的组件销毁时解绑其事件回调

methods: {
	onMyGlobalEvent(){}
},
mounted() {
	this.$bus.$on('my-global-event', this.onMyGlobalEvent)
},
beforeDestory() {
	this.$bus.$off('my-global-event', this.onMyGlobalEvent)
}

全局消息发布订阅

pubsub-js

  • 安装

npm i pubsub-js

  • 使用
import pubsub from 'pubsub-js'
export default {
  ...
  methods: {
    onClick() {
      // 发布
      pubsub.publish('my-message', 666);
    }
  },
  mounted() {
    // 订阅
    this.pubid = pubsub.subscribe('my-message', (msgName, data) => {
      // 注:如果使用function函数此处this为undefined
      console.log(msgName, data)
    })
  },
  beforeDestroy() {
    // 取消订阅
    pubsub.unscribe(this.pubid);
  }
}

posted on 2022-04-11 22:37  路过君  阅读(37)  评论(0编辑  收藏  举报

导航