21.9.25————已解决
publish和subscribe
- publish("eventName", (name, context, aaa) => {}) //发布一个自定义事件
- subscribe("eventName", callback) // 接受一个自定义的时间,在接受的时候,eventName要和发布的名称保持一致
- unsubscribe("eventName"); // 解除自定义
- subscribeOne() // 发布一个只触发一次的自定义事件
- notify() // 触发已经发布的
问题
pubsub.publish 触发一次
pubsub.subscribe 调用多次
问题描述
在二次封装组件中,组件与表单之间的通信传值,采用pubsub的方式
1.在封装的组件中发布,用'changeComponentHandle'的方式触发
localValue(v, o) {
this.$pubsub.publish('changeComponentHandle', {
name: this.en_key,
type: this.type,
value: this.$data.localValue
})
},
2.在表单中订阅,在mounted挂载阶段进行订阅
mounted() {
// 事件订阅 与组件的传值相关
this.$pubsub.subscribe('changeComponentHandle', (msg, obj) => {
this.changeComponentHandle(obj)
})
},
产生问题
由于有多个表单,在mounted阶段都进行了订阅,即多处订阅,则会产生相关问题
问题解决
2.先执行unsubscribe,再进行订阅
mounted() {
// 多次调用的解决,先取消,再订阅,这样只执行一次。
this.$pubsub.unsubscribe('changeComponentHandle')
// 事件订阅 与组件的传值相关
this.$pubsub.subscribe('changeComponentHandle', (msg, obj) => {
this.changeComponentHandle(obj)
})
},