vue2 中父子组件数据同步 父→子 子→父 如何实现?
v-model=“count” 或者 xxx.sync=“msg”
- v-model 语法糖 完整写法
:value=“count” 和 @input=“count=$event”
- xxx.sync 语法糖 完整写法
:xxx=“msg” 和 @update:xxx=“msg=$event”
现在:一个 v-model 指令搞定,不需要记忆两种语法
vue3 中 v-model 语法糖
借助modelValue和@update:modelValue实现
<cp-radio-btn :modelValue="count" @update:modelValue="count = $event"></cp-radio-btn>
//可以简写为以下:
<cp-radio-btn v-model="count"></cp-radio-btn>
//ts部分
<script setup lang="ts">
defineProps<{
modelValue: number
}>()
defineEmits<{
(e: 'update:modelValue', count: number): void
}>()
</script>
<template>
<div class="cp-radio-btn">
{{ modelValue }}
<button @click="$emit('update:modelValue', modelValue + 1)">+1</button>
</div>
</template>
<style lang="scss" scoped></style>
另一种用法
<cp-radio-btn v-model:count="count"></cp-radio-btn>
<script setup lang="ts">
defineProps<{
count: number
}>()
defineEmits<{
(e: 'update:count', count: number): void
}>()
</script>
<template>
<div class="cp-radio-btn">
{{ count }}
<button @click="$emit('update:count', count + 1)">+1</button>
</div>
</template>
<style lang="scss" scoped></style>
博客介绍了Vue2和Vue3中父子组件数据同步的实现方式。在Vue2中,可通过v-model或xxx.sync语法糖实现,还给出了其完整写法;而在Vue3中,借助modelValue和@update:modelValue,用一个v-model指令就能搞定,无需记忆两种语法。
1778

被折叠的 条评论
为什么被折叠?



