vue3 中 v-model
语法糖
- Vue3中父组件给子组件传值,子组件用defineProps接收;子组件更改父组件传的值,通过emit向父组件传值
- Vue3中只需要
v-model
指令可以支持多个数据在父子组件同步,不再支持.sync
语法 v-model="count"
等价于:modelValue="count" @update:modelValue="count=$event"
直接上案例:
//父组件------------------------------------
<script setup lang="ts">
import { ref } from 'vue'
import ChildOne from '@/components/ChildOne.vue'
const money = ref(10)
const name = ref('小明')
</script>
<template>
<!-- 原始写法 -->
<!-- <child-one
:model-value="money"
@update:model-value="money = $event"
></child-one> -->
<!-- 使用v-model语法糖简化写法 -->
<child-one v-model="money" v-model:name="name"></child-one>
</template>
<style scoped></style>
//子组件--------------------------------
<script setup lang="ts">
defineProps<{
modelValue: number
name: string
}>()
// 子组件更改父组件的值
const emit = defineEmits<{
(e: 'update:modelValue', money: number): void
(e: 'update:name', name: string): void
}>()
</script>
<template>
<div>
<p>钱包{{ modelValue }}</p>
<button @click="emit('update:modelValue', modelValue + 1)">点击加一</button>
<p>姓名:{{ name }}</p>
<button @click="emit('update:name', '更改的姓名')">更改姓名</button>
</div>
</template>
<style scoped></style>