【vue3:v-model】

162 阅读1分钟

结论:

  1. 在vue3里v-model等于:modelValue和@update:modelValue的语法糖,父组件中传给子组件
  2. 相当于vue2中的v-model和.sync结合起来用

手动操作

简单的父子组件双向绑定

父组件

import { ref } from 'vue';
import Children from './Children.vue';
const count = ref(1)
</script>
<template>
<h2>父组件</h2>
<Children :count='count' @changeCount = "count = $event"/>
</template>

子组件

<script lang="ts" setup>
defineProps(['count'])
</script>
<template>
<h2>子组件:{{count}}</h2>
<button @click="$emit('changeCount',233)"> Alter </button>
</template>

逻辑

点击按钮,子组件的值传给父组件,赋给count,数字由1变233

aaa (2).png

父组件通过 :count=count\color{red}{:count='count'} 将count传给子组件

子组件用 defineProps([count])\color{red}{defineProps(['count'])} 接收

子组件 emit(changeCount,233)调用父子间中的emit('changeCount',233) 调用父子间中的 \color{red}{changeCount}$ 方法

使 event=233event = 233(event代表子组件$emit的第二个参数)

模拟v-model的父子组件双向绑定

父组件 :传参 count 改为 modelValue,changeCount改为update:modelValue

<script setup lang="ts">
import { ref } from 'vue';
import Children from './Children.vue';
const count = ref(1)
</script>
<template>
<h2>父组件</h2>
<Children :modelValue='count' @update:modelValue = "count = $event"/>
</template>

子组件 : 接收参数改为modelValue,调用方法改为update:modelValue

<script lang="ts" setup>
defineProps(['modelValue'])
</script>
<template>
<h2>子组件:{{modelValue}}</h2>
<button @click="$emit('update:modelValue',233)"> Alter </button>
</template>

依然可以达到效果,这里传方法支持冒号,所以update:modelValue和modelValue两者无特殊含义

v-model

此时把父组件的

<Children :modelValue='count' @update:modelValue = "count = $event"/>

替换为

<Children v-model="count"/>

此时,点击按钮,依然可以双向绑定 所以v-model等于:modelValue和@update:modelValue的语法糖

多次使用v-model,当.sync使用

父组件

<script setup lang="ts">
import { ref } from 'vue';
import Children from './Children.vue';
const count = ref(1)
const count2 = ref(2)
</script>
<template>
<h2>父组件</h2>
<Children v-model="count"/>
<Children v-model:count2="count2"/>
</template>

子组件

<script lang="ts" setup>
defineProps(['modelValue','count2'])
</script>
<template>
<h2>子组件:{{modelValue}}</h2>
<h2>子组件:{{count2}}</h2>
<button @click="$emit('update:modelValue',233)"> Alter </button>
<button @click="$emit('update:count2',222)"> Alter2 </button>

</template>

通过v-model:newValue 的方式,父组件可以向子组件绑定多个值,而子组件通过 update:newValue 的方式接收

222.png

(ps:可以看出,v-model默认等于v-model:modelValue)

345.gif

完!

期待您的宝贵评论,(ˇωˇ」∠))寄罢...