Skip to main content

组件通信方式

扩展

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'] // 获取到祖先组件传递过来的值

解决自定义指令情况,无法组件通信

在自定义指令钩子里,无法使用传统的方法触发刚创建的组件内部方法

  1. 通过在新组件内部使用 getCurrentInstance 挂载方法解决
<script setup>

import {ref,getCurrentInstance} from 'vue'
const title = ref('')
// 把编辑的方法放到实例上,自定义指令可以调用该方法修改组件中拿到值
const setTitle = (title_)=>{
title.value = title_
}
getCurrentInstance().setTitle = setTitle


  1. 然后在自定义指令的 js 文件中创建该 vue 组件 app = createApp(xxx)
  2. dom = app.mount(dom.createElement('div')) 挂载到 dom 上
  3. 组件挂载了就可以在自定义指令中得到指令的参数,手动执行该函数
// 使用动态绑定,使用方法,v-loading:[loadingText]='..
// binding.arg
const title = binding.arg;
if (typeof title !== "undefined") {
// console.log(el.instance)
app._instance.setTitle(title);
}

题外话

  1. 如何把该 dom 挂到自定义指令所在的标签 el 上?dom 暂存到 el 对象的一个任意属性上,如 instance
  2. 要挂的时候去,instance 找实例,然后 el.appendChild( el.instance.$el),$el 是真正的纯 dom,不再有 vue 的能力
function append(el) {
const style = getComputedStyle(el);
if (["absolute", "fixed", "relative"].indexOf(style.position) === -1) {
addClass(el, relativeCls);
}

el.appendChild(el.instance.$el);
}