组件通信方式
扩展
UI 组件(父组件)封装后,怎么批量传递属性
$attrs
// Children.vue
<div>
<el-input v-bind="this.$attrs"></el-input>
</div>
// App.vue
<FF a="1"</FF>
// a 会透传到 input 上
插槽
如果数据是绑定在组件上, 通过作用域插槽,直接通过入口把组件传到子组件的出口
ref
不推荐,vue 不支持转发局部 ref,ref 会挂到 Children 的顶层上
需要手动把 el-input 上的 ref 复制到 Children 上,再把 Children 的 ref 转发到外部
存疑: 利用 defineExpose 可以获取?
vue 常规的通信方案
整理 vue 中 8 种常规的通信方案
-
通过 props 传递
-
通过 $emit 触发自定义事件
-
使用 ref
-
EventBus
-
$parent 或 $root
-
attrs 与 listeners
-
Provide 与 Inject
-
Vuex
emit
this.$emit('add', good)
<Children @add="cartAdd($event)" />
ref
<Children ref="foo" />
this.$refs.foo // 获取子组件实例,通过子组件实例我们就能拿到对应的数据 ```
EventBus(发布订阅)
使用场景:兄弟组件传值 创建一个中央事件总线 EventBus 兄弟组件通过$emit触发自定义事件,$emit 第二个参数为传递的数值 另一个兄弟组件通过$on 监听自定义事件
// 创建一个中央时间总线类
class Bus {
constructor() {
this.callbacks = {}; // 存放事件的名字
}
$on(name, fn) {
this.callbacks[name] = this.callbacks[name] || [];
this.callbacks[name].push(fn);
}
$emit(name, args) {
if (this.callbacks[name]) {
this.callbacks[name].forEach((cb) => cb(args));
}
}
}
// main.js
Vue.prototype.$bus = new Bus(); // 将$bus挂载到vue实例的原型上
// 另一种方式
Vue.prototype.$bus = new Vue(); // Vue已经实现了Bus的功能
Children1.vue;
this.$bus.$emit("foo");
Children2.vue;
this.$bus.$on("foo", this.handle);
$parent 或$ root
通过共同祖辈$parent或者$root 搭建通信桥连 兄弟组件
this.$parent.on('add',this.add)
另一个兄弟组件
this.$parent.emit('add')
$attrs 与$ listeners
适用场景:祖先传递数据给子孙 设置批量向下传属性$attrs 和 $listeners
$attrs包含了父级作用域中不作为 prop 被识别 (且获取) 的特性绑定 ( class 和 style 除外)。
可以通过 v-bind="$attrs" 传⼊内部组件
// 给Grandson隔代传值,communication/index.vue
<Child2 msg="lalala" @some-event="onSomeEvent"></Child2>
// Child2做展开
<Grandson v-bind="$attrs" v-on="$listeners"></Grandson>
// Grandson使⽤
<div @click="$emit('some-event', 'msg from grandson')">
{{msg}}
</div>
provide 与 inject
在祖先组件定义 provide 属性,返回传递的值 在后代组件通过 inject 接收组件传递过来的值 祖先组件
provide(){
return {
foo:'foo'
}
}
后代组件
inject:['foo'] // 获取到祖先组件传递过来的值