任意组件间通信的两种方法

目录

一、全局事件总线

1、安装全局事件总线

main.js

2、使用事件总线

①、接收数据

②、提供数据

二、消息订阅与发布

1、使用步骤

三、$newTick


一、全局事件总线

定义一个组件$busvue身上,所有组件都能够通过$bus使用自定义方法实现组件间通信

也就是说:全局事件总线是一种组件间的通信方式,适用于任意组件间通信;

1、安装全局事件总线

main.js

new Vue({
    el:'#root',
    ...
    beforeCreate(){
        Vue.prototype.$bus = this //安装全局事件总线,$bus就是当前应用的vm
    }
})

2、使用事件总线

①、接收数据

A组件想要接收数据,则在A组件中给$bus绑定自定义事件,事件的回调留在A组件本身

methods:{
    demo(data){
        ...
    }
}
...
mounted(){
    // 通过hello事件接收到传过来的数据
    this.$bus.$on('hello',(data)=>{
        console.log('收到了数据:',data)
    })
},
beforeDestroy(){
    // 销毁hello事件
    this.$bus.$off('hello')
}

②、提供数据

将xxx数据传递过去,命名为hello事件

this.$bus.$emit('hello',this.xxx)

二、消息订阅与发布

一种组件间的通信方式,适用于任意组件间通信

1、使用步骤

①、安装pubsub:npm i pubsub-js

②、引入:在需要使用到的文件中 import pubsub from 'pubsub-js'

③、接收数据:

A组件想要接收数据,则在A组件中订阅消息,订阅的回调留在A组件中;

methods:{
    demo(data){
        ...
    }
}
...
mounted(){
    this.pid = pubsub.subscribe('xxx',this.demo) //订阅消息
}

④、提供数据:pubsub.publish('xxx',数据)

⑤、在beforeDestroy钩子中,使用PubSub.unsubscribe(pid)取消订阅

三、$newTick

nextTick所指定的回调会在DOM节点更新完毕之后再执行

语法:this.nextTick(回调函数)

作用:在下一次DOM更新结束之后执行其指定的回调

this.$nextTick(function(){
                this.$refs.inputTitle.focus()
            })

猜你喜欢

转载自blog.csdn.net/weixin_46376652/article/details/125797167
今日推荐