原文链接 : 7个 Vue3 中的组件通信形式

前言

本文采纳<script setup />的编写形式,比options API更自在。而后咱们会讲以下七种组件通信形式:

  • props
  • emit
  • v-model
  • refs
  • provide/inject
  • eventBus
  • vuex/pinia

举个例子

本文将应用如下演示,如下图所示:

上图中,列表和输入框别离是父组件和子组件。依据不同的通信形式,会调整父子组件。

Props

props 是 Vue 中最常见的父子通信形式,应用起来也比较简单。

依据下面的demo,咱们在父组件中定义了数据和对数据的操作,子组件只渲染一个列表。

父组件代码如下:

<template>  <!-- child component -->  <child-components :list="list"></child-components>  <!-- parent component -->  <div class="child-wrap input-group">    <input      v-model="value"      type="text"      class="form-control"      placeholder="Please enter"    />    <div class="input-group-append">      <button @click="handleAdd" class="btn btn-primary" type="button">        add      </button>    </div>  </div></template><script setup>import { ref } from 'vue'import ChildComponents from './child.vue'const list = ref(['JavaScript', 'HTML', 'CSS'])const value = ref('')// event handling function triggered by addconst handleAdd = () => {  list.value.push(value.value)  value.value = ''}</script>

子组件只须要渲染父组件传递的值。

代码如下:

<template>  <ul class="parent list-group">    <li class="list-group-item" v-for="i in props.list" :key="i">{{ i }}</li>  </ul></template><script setup>import { defineProps } from 'vue'const props = defineProps({  list: {    type: Array,    default: () => [],  },})</script>

Emit

Emit也是Vue中最常见的组件通信形式,用于子组件向父组件传递音讯。

咱们在父组件中定义列表,子组件只须要传递增加的值。

子组件代码如下:

<template>  <div class="child-wrap input-group">    <input      v-model="value"      type="text"      class="form-control"      placeholder="Please enter"    />    <div class="input-group-append">      <button @click="handleSubmit" class="btn btn-primary" type="button">        add      </button>    </div>  </div></template><script setup>import { ref, defineEmits } from 'vue'const value = ref('')const emits = defineEmits(['add'])const handleSubmit = () => {  emits('add', value.value)  value.value = ''}</script>

点击子组件中的【增加】按钮后,咱们会收回一个自定义事件,并将增加的值作为参数传递给父组件。

父组件代码如下:

<template>  <!-- parent component -->  <ul class="parent list-group">    <li class="list-group-item" v-for="i in list" :key="i">{{ i }}</li>  </ul>  <!-- child component -->  <child-components @add="handleAdd"></child-components></template><script setup>import { ref } from 'vue'import ChildComponents from './child.vue'const list = ref(['JavaScript', 'HTML', 'CSS'])// event handling function triggered by addconst handleAdd = value => {  list.value.push(value)}</script>

在父组件中,只须要监听子组件的自定义事件,而后执行相应的增加逻辑即可。

v-model

v-modelVue中一个优良的语法糖,比方上面的代码。

<ChildComponent v-model:title="pageTitle" />

这是以下代码的简写模式

<ChildComponent :title="pageTitle" @update:title="pageTitle = $event" />

这的确容易了很多。当初咱们将应用v-model来实现下面的示例。

子组件代码如下:

<template>  <div class="child-wrap input-group">    <input      v-model="value"      type="text"      class="form-control"      placeholder="Please enter"    />    <div class="input-group-append">      <button @click="handleAdd" class="btn btn-primary" type="button">        add      </button>    </div>  </div></template><script setup>import { ref, defineEmits, defineProps } from 'vue'const value = ref('')const props = defineProps({  list: {    type: Array,    default: () => [],  },})const emits = defineEmits(['update:list'])// Add actionconst handleAdd = () => {  const arr = props.list  arr.push(value.value)  emits('update:list', arr)  value.value = ''}</script>

在子组件中,咱们先定义propsemits,增加实现后再收回指定的事件。

留神:update:*Vue中固定的写法,*代表props中的一个属性名。

在父组件中应用比较简单,代码如下:

<template>  <!-- parent component -->  <ul class="parent list-group">    <li class="list-group-item" v-for="i in list" :key="i">{{ i }}</li>  </ul>  <!-- child component -->  <child-components v-model:list="list"></child-components></template><script setup>import { ref } from 'vue'import ChildComponents from './child.vue'const list = ref(['JavaScript', 'HTML', 'CSS'])</script>

Refs

应用API选项时,咱们能够通过this.$refs.name获取指定的元素或组件,但在组合API中不行。如果咱们想通过ref获取,须要定义一个同名的Ref对象,在组件挂载后能够拜访。

示例代码如下:

<template>  <ul class="parent list-group">    <li class="list-group-item" v-for="i in childRefs?.list" :key="i">      {{ i }}    </li>  </ul>  <!-- The value of the child component ref is the same as that in the <script> -->  <child-components ref="childRefs"></child-components>  <!-- parent component --></template><script setup>import { ref } from 'vue'import ChildComponents from './child.vue'const childRefs = ref(null)</script>

子组件代码如下:

<template>  <div class="child-wrap input-group">    <input      v-model="value"      type="text"      class="form-control"      placeholder="Please enter"    />    <div class="input-group-append">      <button @click="handleAdd" class="btn btn-primary" type="button">        add      </button>    </div>  </div></template><script setup>import { ref, defineExpose } from 'vue'const list = ref(['JavaScript', 'HTML', 'CSS'])const value = ref('')// event handling function triggered by addconst handleAdd = () => {  list.value.push(value.value)  value.value = ''}defineExpose({ list })</script>
留神:默认状况下,setup组件是敞开的,通过模板ref获取组件的公共实例。如果须要公开,须要通过defineExpose API公开。

provide/inject

provide/inject是 Vue 中提供的一对 API。无论层级多深,API 都能够实现父组件到子组件的数据传递。

父组件代码如下所示:

<template>  <!-- child component -->  <child-components></child-components>  <!-- parent component -->  <div class="child-wrap input-group">    <input      v-model="value"      type="text"      class="form-control"      placeholder="Please enter"    />    <div class="input-group-append">      <button @click="handleAdd" class="btn btn-primary" type="button">        add      </button>    </div>  </div></template><script setup>import { ref, provide } from 'vue'import ChildComponents from './child.vue'const list = ref(['JavaScript', 'HTML', 'CSS'])const value = ref('')// Provide data to child components.provide('list', list.value)// event handling function triggered by addconst handleAdd = () => {  list.value.push(value.value)  value.value = ''}</script>

子组件代码如下所示:

<template>  <ul class="parent list-group">    <li class="list-group-item" v-for="i in list" :key="i">{{ i }}</li>  </ul></template><script setup>import { inject } from 'vue'// Accept data provided by parent componentconst list = inject('list')</script>
留神:应用provide进行数据传输时,尽量应用readonly封装数据,防止子组件批改父组件传递的数据。

eventBus

Vue3 中移除了eventBus,但能够借助第三方工具来实现。Vue 官网举荐应用mitttiny-emitter

在大多数状况下,不倡议应用全局事件总线来实现组件通信。尽管比较简单粗犷,然而保护事件总线从久远来看是个大问题,这里就不解释了。无关详细信息,您能够浏览特定工具的文档。

7、vuex/pinia

VuexPinia是 Vue3 中的状态管理工具,应用这两个工具能够轻松实现组件通信。因为这两个工具都比拟弱小,这里就不一一展现了。无关详细信息,请参阅文档。