Skip to content

组件通信

组件之间的通信是一个核心概念, 不同组件需要共享数据、传递消息或协调行为, 就需要有效的通信机制

Vue3组件通信与Vue2的区别:

  • Vuex换成了Pinia
  • .sync优化到了v-model
  • $listeners所有东西合并到了$attrs
  • 移除了$children
  • 移除了事件总线, 使用mitt代替

常用搭配形式

组件关系传递方式
父传子1. props, 2. v-model, 3.$refs, 4. 默认插槽、具名插槽
子传父1. props, 2. 自定义事件, 3. v-model, 4. $parent
祖传孙 / 孙传祖1. $attr, 2. provide inject
兄弟间 / 任意组件间1. mitt, 2. pinia

props

props是使用频率最高的一种通信方式, 通常用于父子组件间传参

  • 父 => 子: 属性值是非函数

  • 子 => 父: 属性值是函数

  • 父组件代码示例

vue
<template>
  <div class="father">
    <h3>父组件</h3>
    <h4>我的车: {{ car }}</h4>
    <h4>儿子给的玩具: {{ toy }}</h4>
    <Child :car="car" :getToy="getToy" />
  </div>
</template>

<script setup lang="ts" name="Father">
  import Child from './Child.vue'
  import { ref } from 'vue'

  // 数据
  const car = ref('奔驰')
  const toy = ref()

  // 方法
  function getToy(value: string) {
    toy.value = value
  }
</script>
  • 子组件代码示例
vue
<template>
  <div class="child">
    <h3>子组件</h3>
    <h4>我的玩具: {{ toy }}</h4>
    <h4>父给我的车: {{ car }}</h4>
    <button @click="getToy(toy)">玩具给父亲</button>
  </div>
</template>

<script setup lang="ts" name="Child">
  import { ref } from 'vue'
  const toy = ref('奥特曼')

  defineProps(['car', 'getToy'])
</script>

自定义事件

自定义事件常用于: 子 => 父

区分原生事件与自定义事件

原生事件:

  • 事件名是特定的, 如click, mosueenter
  • 事件对象$event是包含了事件相关信息的对象, 如pageXpageYtargetkeyCode

自定义事件:

  • 事件名是任意名称
  • 事件对象$event: 是调用emit时所提供的数据, 可以是任意类型

使用自定义事件通信

  • 父组件代码示例
vue
<template>
  <div class="father">
    <!-- 在父组件中给子组件绑定自定义事件 -->
    <Child @send-toy="toy = $event" />
  </div>
</template>
  • 子组件代码示例
ts
// 子组件中触发事件
this.$emit('send-toy', 具体数据)

mitt

mitt与消息订阅与发布pubsub功能类似, 可以实现任意组件间通信

安装

bash
# 安装 mitt
npm i mitt

使用

第一步: 新建文件src/utils/emitter.ts

  • 代码示例
ts
// 引入 mitt 
import mitt from 'mitt'

// 创建 emitter
const emitter = mitt()

/*
// 绑定事件
emitter.on('abc', (value) => {
  console.log('abc事件被触发', value)
})
emitter.on('xyz', (value) => {
  console.log('xyz事件被触发', value)
})

setInterval(() => {
  // 触发事件
  emitter.emit('abc', 666)
  emitter.emit('xyz', 777)
}, 1000);

setTimeout(() => {
  // 清理事件
  emitter.all.clear()
}, 3000)
*/

// 创建并暴露 mitt
export default emitter

第二步: 在接收数据的组件中绑定事件, 同时在销毁前解绑事件

  • 代码示例
ts
import emitter from '@/utils/emitter'
import { onUnmounted } from 'vue'

// 绑定事件
emitter.on('send-toy', (value) => {
  console.log('send-toy事件被触发', value)
})

onUnmounted(() => {
  // 解绑事件
  emitter.off('send-toy')
})

第三步: 提供数据的组件在合适的时候触发事件

ts
import emitter from '@/utils/emitter'

function sendToy() {
  // 触发事件
  emitter.emit('send-toy', toy.value)
}

注意

注意这个重要的内置关系, 总线依赖着这个内置关系

v-model

v-model可以实现父 <=> 子直接互相通信

前序知识

  • v-model的本质
vue
<!-- 使用 v-model 指令 -->
<input type="text" v-model="username"></input>

<!-- v-model 的本质 -->
<input
  type="text"
  :value="username"
  @input="username = (<HTMLInputElement>$event.target).value">
</input>

组件标签上的 v-model

组件标签上的v-model本质: :modelValue + update:modelValue事件

  • 父组件
vue
<!-- 组件标签上使用 v-model 指令 -->
<AtCatInput v-model="username"></AtCatInput>

<!-- 组件标签上 v-model 的本质 -->
<AtCatInput
  :modelValue="username"
  @update:model-value="username = $event">
</AtCatInput>
  • AtCatInput组件中
vue
<template>
<div class="box">
  <!-- 将接收的 value 值赋给 input 元素的 value 属性, 目的是为了呈现数据 -->
  <!-- 给 input 元素绑定原生 input 事件, 触发 input 事件时, 进而触发 update:model-value 事件 -->
  <input 
    type="text"
    :value="modelValue"
    @input="emit('update:model-value', $event.target.value)">
  </input>
</div>
</template>

<script setup lang="ts" name="AtCatInput">
  // 接收 props
  defineProps(['modelValue'])

  // 声明事件
  const emit = defineEmits(['update:model-value'])
</script>
  • 可以更换value, 例如改成abc
vue
<!-- 也可以更换 value,例如改成 abc-->
<AtCatInput v-model:abc="username"></AtCatInput>

<!-- 上面代码的本质 -->
<AtCatInput
  :abc="username"
  @update:abc="username = $event">
</AtCatInput>
  • AtCatInput组件中
vue
<template>
  <div class="box">
    <input
      type="text"
      :value="abc"
      @input="emit('update:abc', $event.target.value)">
    </input>
  </div>
</template>

<script setup lang="ts" name="AtCatInput">
  // 接收 props
  defineProps(['abc'])
  // 声明事件
  const emit = defineEmits(['update:abc'])
</script>
  • 既然value可以更换, 那么就可以在组件标签上多次使用v-model
vue
<AtCatInput v-model:abc="username" v-model:xyz="password"></AtCatInput>

$attrs

$attrs用于实现当前组件的父组件当前组件的子组件通信, 祖 => 孙

$attrs是一个对象, 包含所有父组件传入的标签属性

注意

$attrs会自动排除props中声明的属性, 可以认为声明过的 props 被子组件自己消费

  • 父组件
vue
<template>
  <div class="father">
    <h3>父组件</h3>
    <Child :a="a" :b="b" :c="c" :d="d" v-bind="{ x: 100, y: 200 }" :updateA="updateA" />
  </div>
</template>

<script setup lang="ts" name="Father">
  import Child from './Child.vue'
  import { ref } from 'vue';
  let a = ref(1)
  let b = ref(2)
  let c = ref(3)
  let d = ref(4)

  function updateA(value){
    a.value = value
  }
</script>
  • 子组件
vue
<template>
  <div class="child">
    <h3>子组件</h3>
    <GrandChild v-bind="$attrs" />
  </div>
</template>

<script setup lang="ts" name="Child">
  import GrandChild from './GrandChild.vue'
</script>
  • 孙组件
vue
<template>
  <div class="grand-child">
    <h3>孙组件</h3>
    <h4>a: {{ a }}</h4>
    <h4>b: {{ b }}</h4>
    <h4>c: {{ c }}</h4>
    <h4>d: {{ d }}</h4>
    <h4>x: {{ x }}</h4>
    <h4>y: {{ y }}</h4>
    <button @click="updateA(666)">点我更新A</button>
  </div>
</template>

<script setup lang="ts" name="GrandChild">
  defineProps(['a', 'b', 'c', 'd', 'x', 'y', 'updateA'])
</script>

$refs 和 $parent

概述

  • $refs用于父 => 子
  • $parent用于子 => 父
属性说明
$refs值为对象, 包含所有被ref属性标识的DOM元素或组件实例
$parent值为对象, 当前组件的父组件实例对象

provide 和 inject

实现祖孙组件直接通信, 祖 <=> 孙

  • 在祖先组件中通过provide配置向后代组件提供数据
  • 在后代组件中通过inject配置来声明接收数据

使用

第一步: 在父组件中使用provide提供数据

vue
<template>
  <div class="father">
    <h3>父组件</h3>
    <h4>资产: {{ money }}</h4>
    <h4>汽车: {{ car }}</h4>
    <button @click="money += 1">资产+1</button>
    <button @click="car.price += 1">汽车价格+1</button>
    <Child />
  </div>
</template>

<script setup lang="ts" name="Father">
  import Child from './Child.vue'
  import { ref, reactive, provide } from 'vue'

  // 数据
  let money = ref(100)
  let car = reactive({
    brand: '奔驰',
    price: 100
  })

  // 用于更新 money 的方法
  function updateMoney(value: number) {
    money.value += value
  }

  // 提供数据
  provide('moneyContext', { money, updateMoney })
  provide('car', car)
</script>

注意

子组件中不用编写任何东西, 是不受到任何影响的

第二步: 孙组件中使用inject配置项接受数据

vue
<template>
  <div class="grand-child">
    <h3>我是孙组件</h3>
    <h4>资产: {{ money }}</h4>
    <h4>汽车: {{ car }}</h4>
    <button @click="updateMoney(6)">点我</button>
  </div>
</template>

<script setup lang="ts" name="GrandChild">
  import { inject } from 'vue'

  // 注入数据
  let { money, updateMoney } = inject('moneyContext', { money: 0, updateMoney: (x: number) => {} })
  let car = inject('car')
</script>

pinia

参考 Pinia 状态管理

slot

插槽是Vue中一种强大的内容分发机制, 允许父组件向子组件传递模板内容

Vue3中的插槽系统与Vue 2基本保持一致, 但有一些语法改进和性能优化

默认插槽

  • 父组件
vue
<Category title="今日热门游戏">
  <ul>
    <li v-for="g in games" :key="g.id">{{ g.name }}</li>
  </ul>
</Category>
  • 子组件
vue
<template>
  <div class="item">
    <h3>{{ title }}</h3>
    <!-- 默认插槽 -->
    <slot></slot>
  </div>
</template>

具名插槽

  • 父组件
vue
<Category title="今日热门游戏">
  <template v-slot:s1>
    <ul>
      <li v-for="g in games" :key="g.id">{{ g.name }}</li>
    </ul>
  </template>
  <template #s2>
    <a href="/more">更多</a>
  </template>
</Category>
  • 子组件
vue
<template>
  <div class="item">
    <h3>{{ title }}</h3>
    <slot name="s1"></slot>
    <slot name="s2"></slot>
  </div>
</template>

作用域插槽

数据在组件的自身, 但根据数据生成的结构需要组件的使用者来决定

比如新闻数据在News组件中, 但使用数据所遍历出来的结构由App组件决定

  • 父组件
vue
<!-- 三种方式都可以 -->
<!-- <Game v-slot:default="params"> -->
<!-- <Game #default="params"> -->
<Game v-slot="params">
  <ul>
    <li v-for="g in params.games" :key="g.id">{{ g.name }}</li>
  </ul>
</Game>
  • 子组件
vue
<template>
  <div class="category">
    <h2>今日游戏榜单</h2>
    <slot :games="games" a="哈哈"></slot>
  </div>
</template>

<script setup lang="ts" name="Category">
  import { reactive } from 'vue'
  let games = reactive([
    { id: 'asgdytsa02', name: '王者荣耀' },
    { id: 'asgdytsa01', name: '英雄联盟' },
    { id: 'asgdytsa03', name: '红色警戒' },
    { id: 'asgdytsa04', name: '斗罗大陆' }
  ])
</script>