全局事件总线以及消息订阅

安装全局事件总线:

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

 

上一篇:常用的vue组件传值


下一篇:vue兄弟组件之间值的传输