vue3 组合式API <script setup>中子组件之间传值逻辑

下面介绍以下七种组件通信方式:

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

1. Props

父组件代码如下:

<template>
  <!-- child component -->
  <child-components :list="list"></child-components>
  
  <!-- parent component -->
  <button @click="handleAdd"  type="button">add</button>

</template>
<script setup>
import { ref } from 'vue'
import ChildComponents from './child.vue'
const list = ref(['JavaScript', 'HTML', 'CSS'])


const handleAdd = () => {
  list.value.push('vue')
}
</script>

子组件只需要渲染父组件传递的值。代码如下:

<template>
  <ul>
    <li 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

子组件代码如下:

<template>
  <div>
    <input v-model="value" type="text"/>
    <div>
      <button @click="handleSubmit" 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>
    <li 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'])

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" />

子组件

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

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

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

<template>
  <!-- parent component -->
  <ul>
    <li 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

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

示例代码如下:

<template>
  <ul>
    <li v-for="i in childRefs?.list" :key="i">
      {{ i }}
    </li>
  </ul>
 
  <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>
    <input v-model="value" type="text"/>
    <div>
      <button @click="handleAdd" type="button">add</button>
    </div>
  </div>
</template>
<script setup>
import { ref, defineExpose } from 'vue'
const list = ref(['JavaScript', 'HTML', 'CSS'])
const value = ref('')

const handleAdd = () => {
  list.value.push(value.value)
  value.value = ''
}
defineExpose({ list })
</script>

注意:默认情况下,setup 组件是关闭的,通过模板 ref 获取组件的公共实例。如果需要公开,需要通过defineExpose API 公开。

5. provide/inject

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

父组件

<template>
  <!-- child component -->
  <child-components></child-components>
  <!-- parent component -->
  <div>
    <input v-model="value" type="text"/>
    <div>
      <button @click="handleAdd" 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('list', list.value)

const handleAdd = () => {
  list.value.push(value.value)
  value.value = ''
}
</script>
  • 子组件
<template>
  <ul>
    <li v-for="i in list" :key="i">{{ i }}</li>
  </ul>
</template>
<script setup>
import { inject } from 'vue'

const list = inject('list')
</script>

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

6. eventBus

Vue 3 中移除了 eventBus,但可以借助第三方工具来完成。Vue 官方推荐使用 mitt 或 tiny-emitter。在大多数情况下,不建议使用全局事件总线来实现组件通信。虽然比较简单粗暴,但是维护事件总线从长远来看是个大问题。

  • 首先,需要安装 mitt :
npm install --save mitt
  • 然后在 libs 文件夹下,创建一个 bus.ts 文件,内容和旧版写法其实是一样的,只不过是把 Vue 实例,换成了 mitt 实例。
import mitt from 'mitt';
export default mitt();
  • 创建和移除监听事件

在需要暴露交流事件的组件里,通过 on 配置好接收方法,同时为了避免路由切换过程中造成事件多次被绑定,多次触发,需要在适当的时机 off 掉:

import { defineComponent, onBeforeUnmount } from 'vue'
import bus from '@libs/bus'

export default defineComponent({
  setup () {
    // 定义一个打招呼的方法
    const sayHi = (msg: string = 'Hello World!'): void => {
      console.log(msg);
    }

    // 启用监听
    bus.on('sayHi', sayHi);

    // 在组件卸载之前移除监听
    onBeforeUnmount( () => {
      bus.off('sayHi', sayHi);
    })
  }
})
  • 调用监听事件

在需要调用交流事件的组件里,通过 emit 进行调用:

import { defineComponent } from 'vue'
import bus from '@libs/bus'

export default defineComponent({
  setup () {
    // 调用打招呼事件,传入消息内容
    bus.emit('sayHi', '哈哈哈哈哈哈哈哈哈哈哈哈哈哈');
  }
})

旧项目升级 EventBus

在 Vue 3.x 的 EventBus,我们可以看到它的 API 和旧版是非常接近的,只是去掉了 $ 符号。

如果你要对旧的项目进行升级改造,因为原来都是使用了 $on 、 $emit 等旧的 API ,一个一个组件去修改成新的 API 肯定不现实。

我们可以在创建 bus.ts 的时候,通过自定义一个 bus 对象,来挂载 mitt 的 API 。

在 bus.ts 里,改成以下代码:

import mitt from 'mitt';

// 初始化一个 mitt 实例
const emitter = mitt();

// 定义一个空对象用来承载我们的自定义方法
const bus: any = {};

// 把你要用到的方法添加到 bus 对象上
bus.$on = emitter.on;
bus.$emit = emitter.emit;

// 最终是暴露自己定义的 bus
export default bus;

这样我们在组件里就可以继续使用 bus.$on 、bus.$emit 等以前的老 API 了,不影响我们旧项目的升级使用。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大熋

携手一起攻克bug

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值