组件的自定义事件(子 => 父)
- 一种组件中通信的方式,适用于:子组件 => 父组件
- 适用场景:A是父组件,B是子组件,B给A传数据,就要在A中给B绑定自定义事件(事件的回调在A中)
- 绑定自定义事件:
在父组件中:(xxx为自定义事件名)(demo为子组件名)
方法一:<demo @xxx="test">
方法二:<demo ref="demo"><demo> ... mounted(){ this.$refs.xxx.$on('xxx',this.test) } ```
- 若想让自定义事件只能触发一次,可以使用
once
修饰符,或$once
方法 - 触发自定义事件:
this.$emit('xxx',数据)
(写在子组件中) - 解绑自定义事件:
this.$off('xxx')
(写在父组件中) - ⚠️:通过
this.$refs.xxx.$on('xxx',回调函数)
绑定自定义事件时,回调函数要么配置在methods
中,要么用箭头函数。否则this指向会出问题
全局事件总线(任意之间)
- 适用于任意组件之间的通信
- 安装全局事件总线:
new Vue({
....
beforeCreate() {
// 安装全局事件总线,$bus就是当前应用的app
Vue.prototype.$bus = this;
}
})
- 使用事件总线:
- 接收数据:A组件想接收数据,则在A组件中给
$bus
绑定自定义事件,事件的回调留在A组件自身
methods: { demo(data) { ... } } ... mounted() { this.$bus.$on('xxx',this.demo) }
- 提供数据:
this.$bus.$emit('xxx',数据)
- 接收数据:A组件想接收数据,则在A组件中给
- 最好在
beforeDestroy
钩子中,用$off
去解绑当前组件用到的事件(谁$on
了谁$off
)
消息订阅与发布(任意之间)
同样适用于任意组件之间的通信
使用步骤:
- 安装pubsub:
npm install 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.unsubscibe(pid)
去取消订阅