PubSub 是“发布-订阅”设计模式,也可以作为第三方库使用;$emit 是 Vue 中触发组件事件的方法。两者都基于发布-订阅思想,但 $emit 主要用于父子组件通信,PubSub 更适合任意组件或模块之间的解耦通信。
1.PubSub
- 通信范围:任意组件、任意模块
- 发布方式:this.PubSub.publish
- 订阅方式:this.PubSub.subscribe
- 取消订阅:this.PubSub.unsubscribe
- 引入:main.js引入并挂载全局
importPubSubfrom'pubsub-js'Vue.prototype.PubSub=PubSub- 发布:
this.PubSub.publish("catPath",v);这里的 this.subscribe 不是订阅函数本身,而是 subscribe 返回的订阅 token。
- 订阅:
mounted(){//监听三级分类消息的变化this.subscribe=this.PubSub.subscribe('catPath',(msg,val)=>{this.catId=val[val.length-1]this.getCatBrands()})},- 销毁
beforeDestroy(){this.PubSub.unsubscribe(this.subscribe)//销毁订阅},//生命周期 - 销毁之前2.$emit
- 通信范围:父子组件
- 子组件发布事件:this.$emit(‘update:catelogPath’, v)
- 父组件监听事件:@update:catelogPath 或 .sync
- 不需要手动取消订阅,组件销毁后监听自然失效
父组件:
<el-form-item label="所属分类"prop="catelogId"><category-cascader:catelogPath.sync="catelogPath"></category-cascader></el-form-item>子组件:
data(){//这里存放数据return{setting:{value:"catId",label:"name",children:"children"},categorys:[],paths:this.catelogPath};},watch:{catelogPath(v){// ← 方向①:父 → 子this.paths=this.catelogPath;},paths(v){//// ① 只通知“直接父组件”this.$emit("update:catelogPath",v);//// ② 广播给“任意订阅者”this.PubSub.publish("catPath",v);}},父到子:
- 当父组件改了传进来的 catelogPath,把新值同步给内部的 paths,级联框才会显示出来。
子到父: - 用户在级联框里选了分类,paths 变了,通过 .sync($emit(“update:catelogPath”, v))把值回传给父组件。
补充::
catelogPath.sync="catelogPath"等价于:catelogPath="catelogPath"@update:catelogPath="catelogPath = $event"