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>
相关推荐
自由与自然6 小时前
栅格布局常用用法
开发语言·前端·javascript
Violet_YSWY6 小时前
讲一下ruoyi-vue3的前端项目目录结构
前端·javascript·vue.js
这是你的玩具车吗6 小时前
转型成为AI研发工程师之路
前端·ai编程
Drift_Dream6 小时前
在Vue样式中使用JavaScript 变量(CSS 变量注入)
前端
C_心欲无痕6 小时前
vue3 - toRaw获取响应式对象(如由reactive创建的)的原始对象
前端·javascript·vue.js
PlankBevelen6 小时前
手搓实现简易版 Vue2 响应式系统
前端
LoveDreaMing6 小时前
MCP入门梳理
前端·typescript·mcp
小林攻城狮6 小时前
一个基于 canvas 的 pdf 图片分页切割方法
前端·javascript
老华带你飞6 小时前
学生宿舍管理|基于java + vue学生宿舍管理系统(源码+数据库+文档)
java·开发语言·前端·数据库·vue.js·spring boot·后端
一天前6 小时前
一个功能强大的 React Native 拖拽排序组件库,支持单列和多列布局,提供流畅的拖拽体验和自动滚动功能
前端