ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

7个 Vue3 中的组件通信方式

2022-05-18 01:04:33  阅读:111  来源: 互联网

标签:const list 通信 value Vue3 组件 import ref


原文链接 : 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 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>

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 add
const 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 action
const 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 add
const 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 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封装数据,避免子组件修改父组件传递的数据。

eventBus

Vue3 中移除了eventBus,但可以借助第三方工具来完成。Vue 官方推荐使用mitttiny-emitter

在大多数情况下,不建议使用全局事件总线来实现组件通信。虽然比较简单粗暴,但是维护事件总线从长远来看是个大问题,这里就不解释了。有关详细信息,您可以阅读特定工具的文档。

7、vuex/pinia

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

标签:const,list,通信,value,Vue3,组件,import,ref
来源: https://www.cnblogs.com/tzy1997/p/16283059.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有