全局事件总线以及消息订阅
作者:互联网
安装全局事件总线:
main.js:
new Vue({ el:'#app', render: h => h(App), beforeCreate(){ Vue.prototype.$bus = this//安装全局事件总线 } })
传值组件中
methods:{ sendName(){ this.$bus.$emit('hello',this.name) } }
收值组件中
mounted(){ //创建事件hello this.$bus.$on('hello',(data)=>{ console.log('收到数据',data) }) }, //用完记得销毁$bus里的事件 beforeDestroy(){ this.$bus.$off('hello') }
------------------------------------------------------------------------------------------------------------------------------------------------
安装消息订阅与发布
npm i pubsub-js
传值组件
import pubsub from 'pubsub-js' export default{ name:'Student', data() { return{ name:'张三', myage:18 } }, methods:{ sendName(){ pubsub.publish('hello',this.name) } } }
接受数据组件
import pubsub from 'pubsub-js' ****** mounted(){ this.pubId = pubsub.subscribe('hello',(msgName,data)=>{ console.log('消息已订阅',data) }) }, beforeDestory(){ pubsub.unsubscribe(this.pubId) }
标签:订阅,name,bus,总线,js,全局,data,hello,pubsub 来源: https://www.cnblogs.com/alannero/p/15317085.html