vue3中的v-model语法糖

Vue2的v-model默认解析成 :value 与 @input

Vue3的 V-model 默认解析成 :modelValue 与 @update:modelValue

vue3中只需要 v-model 指令可以支持对个数据在父子组件同步,不再支持 .sync 语法

vue3 中 v-model 语法糖
:modelValue="count"@update:modelValue="count=$event"

vue3 中 v-model:xxx 语法糖?
:xxx="count"@update:xxx="count=$event"

方式一 通过 v-model 解析成 modelValue @update:modelValue

子组件

html 复制代码
<script setup lang="ts">
defineProps<{
  modelValue: number
}>()

defineEmits<{ (e: 'update:modelValue', count: number): void }>()
</script>

<template>
  <div>
    计数器{{ modelValue
    }}<button @click="$emit('update:modelValue', modelValue + 1)">+1</button>
  </div>
</template>

<style lang="scss" scoped></style>

父组件

html 复制代码
<script setup lang="ts">
const count = ref(10)
</script>
<template>
 <!--组件 -->
    <!--<cp-radio-btn
     :model-value="count"
     @updata:model-value="count = $event"
   ></cp-radio-btn>-->
    <!--  :model-value="count"@updata:model-value="count = $event"
    以这样的形式写,就可以简写为 v-model="count"依旧生效 -->
  <cp-radio-btn v-model="count"></cp-radio-btn>
</template>

<style lang="scss" scoped></style>

点击按钮,计数器+1

方式二: 通过 v-model:count 解析成 count @update:count

子组件

html 复制代码
<script setup lang="ts">
defineProps<{
  count: number
}>()

defineEmits<{ (e: 'update:count', count: number): void }>()
</script>

<template>
  <div>
    计数器{{ count }}
    <button @click="$emit('update:count', count + 1)">+1</button>
  </div>
</template>

<style lang="scss" scoped></style>

父组件

html 复制代码
<script setup lang="ts">
const count = ref(10)
</script>
<template>
 <!--组件 -->
  <cp-radio-btn v-model:count="count"></cp-radio-btn>
</template>

<style lang="scss" scoped></style>
相关推荐
Mintopia8 分钟前
🇨🇳 Next.js 在国内场景下的使用分析与实践指南
前端·后端·全栈
Mintopia28 分钟前
深度伪造检测技术在 WebAIGC 场景中的应用现状
前端·javascript·aigc
BUG_Jia28 分钟前
如何用 HTML 生成 PC 端软件
前端·javascript·html·桌面应用·1024程序员节
木易 士心30 分钟前
CSS 样式用法大全
前端·css·1024程序员节
皓月Code30 分钟前
第二章、全局配置项目主题色(主题切换+跟随系统)
javascript·css·react.js·1024程序员节
0129252031 分钟前
1.1 笔记 html 基础 初认识
前端·笔记·html
MoonBit月兔1 小时前
MoonBit Pearls Vol.12:初探 MoonBit 中的 JavaScript 交互
开发语言·javascript·数据库·交互·moonbit
2501_929382651 小时前
[Switch大气层]纯净版+特斯拉版 20.5.0大气层1.9.5心悦整合包 固件 工具 插件 前端等资源合集
前端·游戏·switch·1024程序员节·单机游戏
非凡ghost1 小时前
Tenorshare 4DDiG(数据恢复软件) 最新版
前端·javascript·后端