Vue 3 中的七个组件通信技巧

开发 前端
本文采用<script setup />的写法,比options API更自由。那么我们就来说说以下七种组件通信方式都有哪些吧。

写在前面

本文采用<script setup />的写法,比options API更自由。那么我们就来说说以下七种组件通信方式:

  1. props
  2. emit
  3. v-model
  4. refs
  5. provide/inject
  6. eventBus
  7. vuex/pinia

举个例子

本文将使用下面的演示,如下图所示:

上图中,列表和输入框分别是父组件和子组件。根据不同的通信方式,父子组件会有所调整。

1. 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 add
const 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>

2. 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>

单击子组件中的 [Add] 按钮后,我们发出自定义事件并将添加的值作为参数传递给父组件。

父组件代码如下:

<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 add
const handleAdd = value => {
list.value.push(value)
}
</script>

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

3.v-model

v-model是Vue中一个优秀的语法糖,比如下面的代码。

<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 action
const handleAdd = () => {
const arr = props.list
arr.push(value.value)
emits('update:list', arr)
value.value = ''
}
</script>

在子组件中,我们先定义props和emit,添加完成后,再emit指定的事件。

注意: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>

4. refs

在使用option API时,我们可以通过this.$refs.name获取指定的元素或组件,而在combined 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 add
const handleAdd = () => {
list.value.push(value.value)
value.value = ''
}
defineExpose({ list })
</script>

注意:默认情况下,setup组件是关闭的,通过template ref获取组件的public实例。如果需要暴露,需要通过defineExpose API暴露。

5. 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 add
const 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 component
const list = inject('list')
</script>

注意:使用provide进行数据传递时,尽量用readonly封装数据,避免子组件修改父组件传过来的数据。

6.eventBus

在 Vue 3 中移除了 eventBus,但可以借助第三方工具来完成。Vue 官方推荐 mitt 或 tiny-emitter。大多数情况下,不推荐使用全局事件总线来实现组件通信。虽然比较简单粗暴,但是长期维护event bus是个大问题,这里就不多说了。具体可以阅读具体工具的文档。

7.Vuex && Pinia

Vuex和Pinia是Vue 3中的状态管理工具,使用这两个工具可以轻松实现组件通信。由于这两个工具比较强大,这里就不展示了。有关详细信息,请参阅文档。

最后

以上就是我今天想与你分享的Vue3中的7个组件通信技巧,如果对你有帮助的话,请记得点赞我,关注我,并将这篇文章分享给你的朋友,也许能够帮助到他。

最后,谢谢你的阅读。

责任编辑:华轩 来源: web前端开发
相关推荐

2022-05-06 08:47:10

Vue 3组件前端

2023-12-19 16:50:37

2022-12-12 13:19:11

Vue3开发技巧

2022-11-30 15:33:39

Vue 3组件

2023-03-29 07:54:25

Vue 3插件

2023-09-07 16:28:46

JavaScrip

2021-11-22 12:13:54

Linuxwget 命令

2022-06-23 09:22:57

Vue技巧前端

2022-03-11 12:31:04

Vue3组件前端

2021-08-17 10:08:44

HTML网站网络

2022-04-14 10:40:11

领导者IT团队远程团队

2023-11-06 11:32:46

CSS选择器作用域

2019-09-09 10:32:51

基于意图的网络IBN网络

2023-05-30 09:59:38

2018-05-24 08:47:15

数据存储技巧

2022-07-14 10:34:13

IT领导者CIO首席信息官

2021-06-28 11:46:31

GitLinux

2018-04-27 09:22:21

数据存储技巧

2024-01-09 08:34:56

Vue3.js组件通信

2010-06-09 12:20:34

网络通信协议层
点赞
收藏

51CTO技术栈公众号