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>
相关推荐
摘星编程2 小时前
React Native for OpenHarmony 实战:Linking 链接处理详解
javascript·react native·react.js
胖者是谁2 小时前
EasyPlayerPro的使用方法
前端·javascript·css
EndingCoder3 小时前
索引类型和 keyof 操作符
linux·运维·前端·javascript·ubuntu·typescript
liux35283 小时前
Web集群管理实战指南:从架构到运维
运维·前端·架构
沛沛老爹3 小时前
Web转AI架构篇 Agent Skills vs MCP:工具箱与标准接口的本质区别
java·开发语言·前端·人工智能·架构·企业开发
摘星编程3 小时前
React Native for OpenHarmony 实战:ImageBackground 背景图片详解
javascript·react native·react.js
小光学长3 小时前
基于Web的长江游轮公共服务系统j225o57w(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
前端·数据库
摘星编程4 小时前
React Native for OpenHarmony 实战:Alert 警告提示详解
javascript·react native·react.js
Joe5564 小时前
vue2 + antDesign 下拉框限制只能选择2个
服务器·前端·javascript
WHS-_-20225 小时前
Tx and Rx IQ Imbalance Compensation for JCAS in 5G NR
javascript·算法·5g