[ Vue3 ] 三种方式实现组件数据双向绑定

在这里插入图片描述

Vue3 三种方式实现组件数据双向绑定

Vue 中,组件数据双向绑定是一项非常重要的特性,它使得我们能够轻松地在组件中处理数据的变化并将其同步到视图

比如我们想要在父组件中修改数据能够同步给子组件,并且子组件修改数据也能同步给父组件,使他们数据一方发生变化,则双方都发生改变。

实现组件数据双向绑定有三种写法分别是 常规写法v-modeldefineModel,下面给大家一一演示

常规写法

在点击父组件按钮时修改数据并同步给子组件

<script setup lang="ts">
import { ref } from 'vue';
import Hello from './components/Hello.vue';

const data = ref("Hello World")

// 通过调用该事件完成修改数据的操作
const changeData = (value: string) => {
  data.value = value
}
</script>

<template>
  <h1>{{ data }}</h1>
  <button @click="data = 'Hello Vue3'">修改子组件的数据</button>

  <!-- 简写:<Hello :data="data" @update="data = $event" /> -->
  <Hello :data="data" @update="changeData" />
</template>

点击子组件中的按钮触发父组件的自定义事件 update 绑定的 changeData 方法,并将参数 你好,世界! 传递给父组件的方法: changeData 从而实现更改父组件的数据

<script setup lang="ts">
const props = defineProps<{ data: string }>()
const emit = defineEmits<(e: "update", value: string) => void>()
</script>

<template>
  <h1>{{ data }}</h1>
  <button @click="emit('update', '你好, 世界!')">修改父组件的数据</button>
</template>

可以发现这种写法非常繁琐,子组件修改数据还要通过触发事件来完成

v-model

Vue3 中,使用 v-model 指令来实现组件数据的双向绑定非常简单。我们可以在组件中使用 v-model 指令来绑定一个值,并且在组件内部可以直接操作这个值。

接下来这种写法才是 Vue 主流的方式:

<script setup lang="ts">
import { ref } from 'vue';
import Hello from './components/Hello.vue';

const data = ref("Hello World")
</script>

<template>
  <h1>{{ data }}</h1>
  <button @click="data = 'Hello Vue3'">修改子组件的数据</button>
  
  <!-- 核心代码 -->
  <Hello v-model="data" />
</template>
  1. 在子组件中我们将数据以 modelValue 命名来接收(固定命名)

  2. defineEmits 定义一个修改数据的事件:(e: "update:modelValue", value: string) => void

  3. 通过触发 emit('update:modelValue', '你好, 世界!') 来实现数据的更新操作

<script setup lang="ts">
const props = defineProps<{ modelValue: string }>()
const emit = defineEmits<(e: "update:modelValue", value: string) => void>()
</script>

<template>
  <h1>{{ modelValue }}</h1>
  <button @click="emit('update:modelValue', '你好, 世界!')">修改父组件的数据</button>
</template>

接下来想必大家就会有疑惑了,如果是多个数据需要双向绑定该怎么做呢?其实也很简单:

<script setup lang="ts">
import { ref } from 'vue';
import Hello from './components/Hello.vue';

const data1 = ref("Hello World")
const data2 = ref("Hello World")
</script>

<template>
  <h1>{{ data1 }}</h1>
  <h1>{{ data2 }}</h1>
  <button @click="data1 = 'Hello Vue3'">修改子组件的数据</button>
  <button @click="data2 = 'Hello TypeScript'">修改子组件的数据</button>

  <!-- 核心代码 -->
  <Hello v-model:data1="data1" v-model:data2="data2" />
</template>
<script setup lang="ts">
const props = defineProps<{ data1: string, data2: string }>()
const emit = defineEmits<{ (e: "update:data1", value: string): void, (e: "update:data2", value: string): void }>()
</script>

<template>
  <h1>{{ data1 }}</h1>
  <h1>{{ data2 }}</h1>
  <button @click="emit('update:data1', '你好, 世界!')">修改父组件的数据</button>
  <button @click="emit('update:data2', '你好, 世界!')">修改父组件的数据</button>
</template>

对比一下常规的写法,可以发现不必再通过手动绑定事件就可以达到双向绑定的需求。

而常规写法其实就是这种写法的实现原理

defineModel

学习了上述两种写法后,接下来这种写法你一定会爱不释手,话不多说直接代码演示:

<script setup lang="ts">
import { ref } from 'vue';
import Hello from './components/Hello.vue';

const data = ref("Hello World")
</script>

<template>
  <h1>{{ data }}</h1>
  <button @click="data = 'Hello Vue3'">修改子组件的数据</button>

  <!-- 核心代码 -->
  <Hello v-model="data" />
</template>
<script setup lang="ts">
import { defineModel } from 'vue'
const modelValue = defineModel()
</script>

<template>
  <h1>{{ modelValue }}</h1>
  <button @click="modelValue = '你好, 世界!'">修改父组件的数据</button>
</template>

当然,如果想要实现多个双向数据绑定可以这么做:

<script setup lang="ts">
import { ref } from 'vue';
import Hello from './components/Hello.vue';

const data1 = ref("Hello World")
const data2 = ref("Hello World")
</script>

<template>
  <h1>{{ data1 }}</h1>
  <h1>{{ data2 }}</h1>
  <button @click="data1 = 'Hello Vue3'">修改子组件的数据</button>
  <button @click="data2 = 'Hello TypeScript'">修改子组件的数据</button>

  <!-- 核心代码 -->
  <Hello v-model:data1="data1" v-model:data2="data2" />
</template>
<script setup lang="ts">
import { defineModel } from 'vue'
const data1 = defineModel("data1")
const data2 = defineModel("data2")
</script>

<template>
  <h1>{{ data1 }}</h1>
  <h1>{{ data2 }}</h1>
  <button @click="data1 = '你好, 世界!'">修改父组件的数据</button>
  <button @click="data2 = '你好, 世界!'">修改父组件的数据</button>
</template>

使用该语法糖可以直接调用 defineModel 拿到父组件传递的数据,不需要再使用 defineEmitsdefineProps 就可以操作数据,告别繁琐的组件双向数据绑定。

注意: 该方式仅支持 Vue3.2.0 及以上版本

目前该方式处于Vue官方实验阶段,所以在控制台会出现以下警告:

defineModel() is a compiler-hint helper that is only usable inside <script setup> of a single file component. Its arguments should be compiled away and passing it at runtime has no effect

解决它的办法也很简单,在 vite.config.ts 文件中配置如下代码即可:

export default defineConfig({
  plugins: [
    // 核心代码
    vue({
      script: {
        defineModel: true,
      },
    }),
  ]
});
  • 8
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue3中,通过使用v-model实现父子组件双向数据绑定方式Vue2有所不同。在Vue3中,我们可以使用`emit`和`on`来实现父子组件间的双向绑定数据。 在父组件中,我们可以通过`v-model`指令绑定一个值,并使用`@update:modelValue`事件和`$emit`方法来更新这个值。在子组件中,我们可以通过`props`接收父组件传递的值,并在需要更新该值的时候使用`$emit`触发`update:modelValue`事件。 以下是一个使用Vue3和TypeScript实现父子组件双向绑定数据的示例: 父组件: ```html <template> <div class="father"> <div class="context"> <h1>这是父组件fatherNum:{{ fatherNum }}</h1> <Son v-model="fatherNum"></Son> </div> </div> </template> <script lang="ts"> import { defineComponent, ref } from 'vue'; import Son from '../components/Son.vue'; export default defineComponent({ components: { Son }, setup() { const fatherNum = ref(0); return { fatherNum }; } }); </script> <style scoped> .father { width: 100vw; height: 100vh; } .context { width: 100%; height: 100%; display: flex; justify-content: center; align-items: center; flex-direction: column; } </style> ``` 子组件: ```html <template> <div class="son"> <button @click="increment">增加</button> <button @click="decrement">减少</button> <p>这是子组件sonNum: {{ modelValue }}</p> </div> </template> <script lang="ts"> import { defineComponent, computed, emit } from 'vue'; export default defineComponent({ props: { modelValue: { type: Number, required: true } }, setup(props, { emit }) { const increment = () => { emit('update:modelValue', props.modelValue + 1); }; const decrement = () => { emit('update:modelValue', props.modelValue - 1); }; return { increment, decrement }; } }); </script> <style scoped> .son { display: flex; } </style> ``` 在这个示例中,父组件中的`fatherNum`通过`v-model`指令与子组件中的`modelValue`进行双向数据绑定。父组件中的值变化时,会触发`update:modelValue`事件,子组件监听该事件并根据需要更新自己的值。 希望对你有帮助!<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [vue3+vite+ts--组件使用v-model实现双向绑定vue2&vue3+ts的详细讲解)](https://blog.csdn.net/m0_60893808/article/details/131244155)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值