先来看看vue2的写法:
Vue2
- vue2 中父子组件数据同步 父→子 子→父 实现?
- v-model=“count” 或者 xxx.sync=“msg”
- v-model 语法糖 完整写法?
- :value=“count” 和 @input=“count=$event”
- xxx.sync 语法糖 完整写法?
- :xxx=“msg” 和 @update:xxx=“msg=$event”
Vue3
从 Vue 3.4 开始,推荐的实现方式是使用 defineModel() 宏:
组件v-model
<!-- Child.vue -->
<script setup>
const model = defineModel()
function update() {
model.value++
}
</script>
<template>
<div>parent bound v-model is: {{ model }}</div>
</template>
<!-- Parent.vue -->
<Child v-model="countModel" />
// 使 v-model 必填
const model = defineModel({ required: true })
// 提供一个默认值
const model = defineModel({ default: 0 })
以下是VUE 3.4 之前的写法
父组件里
<template>
<!-- 简写方式 -->
<son-component v-model:count="parentVal"></son-component>
<!-- 等价 -->
<son-component :count="parentVal" @update:count="parentVal=$event"></son-component>
</template>
<script setup lang="ts">
import { onMounted, ref } from "vue";
const parentVal = ref(10)
</script>
子组件里
<template>
<p>父组件传递过来的值:{{ props.count }}</p>
<button @click="countNum">+1</button>
</div>
</template>
<script setup lang="ts">
const props = defineProps<{
count: number
}>()
const emit = defineEmits<{ (e: 'update:count', num: number): void }>()
function countNum() {
emit('update:count', props.count + 1)
}
</script>
== v-model:xxx=‘’ 的固定写法,子组件里 update:(props数据字段)。比如,在这里若是改为update:countVal或其他,是不生效的==
- vue3 中 v-model 语法糖?
- :count=“parentVal” 和 @update:count=“parentVal=$event”
vue3中只需要 v-model 指令可以支持数据在父子组件同步,不再支持 .sync写法