其他方式通信:EventBus(小型项目)、Vuex(大型项目)、$root、$parent
一. 父子组件
1. props 和 $emit
父组件:
<father>
<son :fatherMsg="from father" @sonClick="getSonValue"></son>
</father>
父组件接受子组件emit过来的值
getSonValue(sonVal){
console.log(sonVal) // 'from son'
}
子组件:
<son @click="sendFather"></son>
props 接收父组件传递过来的值
props: ['fatherMsg']
子组件通过click 事件,向父组件传值
sendFather(){
this.$emit('sonClick' , 'from son')
}
注意:props负责获取父组件的传递过来的,props中的值是只读的,不允许修改
若修改,需要找个变量将父组件传递的数值给赋值过来然后对变量进行操作。
但是只适用于props传递的类型为简单数据类型,修改tempVal不会修改fatherMsg的值
若为对象类型,需要深拷贝进行赋值。
data() {
return {
tempVal: this.fatherMsg
}
}
二. 祖孙组件
1.1 $attrs传递属性, $listeners 传递事件
注意:在vue3.0 中$listeners被移除了,将所有属性都集合到attrs里面了
$attrs 包含了父作用域中不作为 prop 被识别 (且获取) 的特性绑定
$listeners 包含了父作用域中的 (不含 .native 修饰器的) v-on 事件监听器
this.$attrs.fatherMsg
this.$listeners.getSonValue() // 若组件存在多层嵌套,无需$emit 逐层触发,只需要$listeners就可以获取父组件中自定义的事件。
1.2 Provide Inject
父组件:
provide() { return{ name:'lili', age:25, todoLength: this.books.length } }
子孙组件:
inject: ['name', 'age', 'todoLength']
1.3. 全局事件总线mitt库
1.3.1 安装 npm install mitt
1.3.2 main.js 注册挂载 或者封装eventbus.js工具类
(vue3 已移除EventBus 事件总线 ,官方建议使用外部的、实现了事件触发器接口的库,例如 mitt 或 tiny-emitter。)
appContext.config.globalProperties.$mitt.on('moneyEvent', (res: number) => {
amount.value = res;
})
或 utils/eventbus.js 封装 eventbus.js
三.兄弟组件
全局事件总线mitt库