用defineModel实现vue子组件间传递数据

一、背景和意义

vue开发中,时常会涉及到子组件之间传递数据。经典的方法是使用propsemit,而vue 3.4+提供的defineModel方法可以用更少的代码实现这一功能。本文提供一个defineModel方法实现子组件间传递数据的示例。

二、经典方法实现子组件间传递数据

经典方法是使用propsemit,父组件代码如下:

html 复制代码
<template>
  <div>
    <h1>value in parent: {{transferValue}}</h1>
    <ChildA :transferValue="transferValue" @changeValue="handleChangeValue"/>
    <ChildB :transferValue="transferValue" />
  </div>
</template>
<script setup>
  import { ref } from "vue";
  const transferValue = ref("Hello");
  const handleChangeValue = newVal => {
    transferValue.value = newVal;
  };
</script>

子组件ChildA.vue的代码如下:

html 复制代码
<template>
  <div>
    <h1>value in ChildA: {{transferValue}}</h1>
    <button @click="changeValue">change value by childA</button>
  </div>
</template>
<script setup>
  defineProps({
    transferValue: ""
  });
  const emits = defineEmits(['changeValue']);
  const changeValue = () => {
    emits("changeValue", "hello2");
  };
</script>

子组件ChildB.vue的代码如下:

html 复制代码
<template>
  <div>
    <h1>value in ChildB: {{transferValue}}</h1>
    <h1>value length in ChildB: {{valueLength}}</h1>
  </div>
</template>
<script setup>
  import { computed } from "vue";
  const props = defineProps({
    transferValue: ""
  });
  const valueLength = computed(() => {
    return props.transferValue?.length || 0;
  });
</script>

运行效果如下:

点击子组件ChildAchange value by childA按钮之后,父组件和两个子组件的数据均发生了变化。

三、实现子组件间传递数据

使用defineModel需要3.4及以上的vue版本。父组件改为:

html 复制代码
<template>
  <div>
    <h1>value in parent: {{transferValue}}</h1>
    <ChildA v-model="transferValue"/>
    <ChildB v-model="transferValue" />
  </div>
</template>
<script setup>
  import { ref } from "vue"
  const transferValue = ref("Hello");
</script>

子组件ChildA改为:

html 复制代码
<template>
  <div>
    <h1>value in ChildA: {{transferValue}}</h1>
    <button @click="changeValue">change value by childA</button>
  </div>
</template>
<script setup>
  const transferValue = defineModel();
  const changeValue = () => {
    transferValue.value = "hello2";
  };
</script>

子组件ChildB改为:

html 复制代码
<template>
  <div>
    <h1>value in ChildB: {{transferValue}}</h1>
    <h1>value length in ChildB: {{valueLength}}</h1>
  </div>
</template>
<script setup>
  import { computed } from "vue";
  const transferValue = defineModel();
  const valueLength = computed(() => {
    return transferValue?.value?.length || 0;
  });
</script>

程序运行效果和前面经典方法的效果一样,但新的defineModel方法代码更少。

相关推荐
程序视点3 小时前
IObit Uninstaller Pro专业卸载,免激活版本,卸载清理注册表,彻底告别软件残留
前端·windows·后端
前端程序媛-Tian3 小时前
【dropdown组件填坑指南】—怎么实现下拉框的位置计算
前端·javascript·vue
嘉琪0014 小时前
实现视频实时马赛克
linux·前端·javascript
烛阴4 小时前
Smoothstep
前端·webgl
若梦plus4 小时前
Eslint中微内核&插件化思想的应用
前端·eslint
爱分享的程序员4 小时前
前端面试专栏-前沿技术:30.跨端开发技术(React Native、Flutter)
前端·javascript·面试
超级土豆粉4 小时前
Taro 位置相关 API 介绍
前端·javascript·react.js·taro
若梦plus4 小时前
Webpack中微内核&插件化思想的应用
前端·webpack
若梦plus4 小时前
微内核&插件化设计思想
前端
柯北(jvxiao)4 小时前
搞前端还有出路吗?如果有,在哪里?
前端·程序人生