组件间通信方式
1. 父子组件通信
2.事件总线
3. 插槽
3.1 默认插槽
3.2 具名插槽
3.3 作用域插槽
4.pub-sub (发布-订阅)
5.vuex
参考下面文档
一.父子组件通信
1.1 父向子传值
父组件中 引入子组件
<Child msg="hello"></Child>
子组件中:
props:['msg']
1.2 子向父传值
父组件中 绑定自定义事件:
<Child msg="hello" @fromChild='getData'></Child>
methods 中定义方法接收数据
methods:{
getData(childData){
console.log(childData)
}
}
子组件中:
this.emit('fromChild','我是子组件传递给父组件的值')
二.事件总线
2.1 main.js中
new Vue({
beforeCreate() {
Vue.prototype.$bus = this;
},
})
2.2 获取消息方:
this.$bus.$on('msg',(data)=>{
console.log(data)
})
2.3 提供消息方
this.$bus.$emit('msg','需要传递的消息内容')
2.4 组件销毁时移除事件
this.$bus.$off() //移除所有事件
this.$bus.$off('msg') //移除指定事件
三. 插槽
3.1 默认插槽
父组件中:
<Child>
<template>
<div>
我是插槽内容
</div>
</template>
</Child>
子组件中
<slot></slot>
3.2 具名插槽
v-slot:插槽名称
父组件中:
<Child>
<template v-slot:headslot>
<div>
我是插槽内容
</div>
</template>
</Child>
子组件中
<slot name='headslot'></slot>
3.3 作用域插槽
父组件中:
<Child>
<template v-slot:headslot='defaultObj'>
<div>
{{defaultObj.data}}
</div>
</template>
</Child>
子组件中
<slot name='headslot' data='我是子组件的值'></slot>
四. pubsub-js
4.1 安装
yarn add pubsub-js
4.2 导入pubsub全局使用
main.js 中
import PubSub from 'pubsub-js'
Vue.prototype.PubSub =PubSub
4.3 发布消息
this.PubSub.publish('msg','要发送的消息')
4.4 接收消息(订阅消息)
this.PubSub.subscribe('msg',(msg,data)=>{
//接收数据
console.log(data)
})
4.5 取消某个订阅消息
this.PubSub.unsubscribe('订阅名称')
//如
this.PubSub.unsubscribe('msg')
4.6 清除所有的订阅
this.PubSub.clearAllSubscriptions();
4.7.获取某个订阅
this.PubSub.getSubscriptions('msg')