Two ways to communicate between arbitrary components

Table of contents

1. Global event bus

1. Install the global event bus

main.js

2. Use the event bus

①. Receive data

②. Provide data

2. Message Subscription and Publishing

1. Steps to use

3. $newTick


1. Global event bus

Define a component $bus on Vue , and all components can use custom methods to communicate between components through $bus ;

That is to say: the global event bus is a communication method between components, which is suitable for communication between any components;

1. Install the global event bus

main.js

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

2. Use the event bus

①. Receive data

If component A wants to receive data , bind custom events to $bus in component A , and the callback of the event stays in component A itself ;

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

②. Provide data

Pass the xxx data to the past and name it the hello event

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

2. Message Subscription and Publishing

A communication method between components, suitable for communication between any components ;

1. Steps to use

①. Install pubsub: npm i pubsub-js

②. Import: import pubsub from 'pubsub-js' in the files that need to be used

③. Receive data:

If component A wants to receive data, subscribe to the message in component A, and the subscribed callback stays in component A;

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

④. Provide data: pubsub.publish('xxx', data)

⑤. In the beforeDestroy hook, use PubSub.unsubscribe(pid) to unsubscribe

3. $newTick

The callback specified by nextTick will be executed after the DOM node is updated

Syntax: this.nextTick(callback function)

Function: Execute the specified callback after the next DOM update ends

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

Guess you like

Origin blog.csdn.net/weixin_46376652/article/details/125797167