vue3自定义多个v-model以及自定义修饰符

从 Vue 3.4 开始,推荐的实现方式是使用 defineModel() 宏:

废话不多说,直接上代码

javascript 复制代码
<!-- Son.vue -->
<script setup>
const model = defineModel()
</script>

<template>
  <span>My input</span> <input v-model="model">
</template>

<!-- Parent.vue -->
<script setup>
import Child from './Child.vue'
import { ref } from 'vue'

const msg = ref('Hello World!')
</script>

<template>
  <h1>{{ msg }}</h1>
  <Child v-model="msg" />
</template>

多个v-model

javascript 复制代码
<!-- Parent.vue -->
<UserName
  v-model:first-name1="first"
  v-model:last-name1="last"
/>
<!-- Son.vue -->
<script setup>
const firstName = defineModel('firstName1')  //这里的参数就是父组件v-model后面的值
const lastName = defineModel('lastName1')
</script>

<template>
  <input type="text" v-model="firstName" />
  <input type="text" v-model="lastName" />
</template>

处理 自定义v-model 修饰符

javascript 复制代码
<!-- Parent.vue -->
<MyComponent v-model.capitalize="myText" />

<!-- Son.vue -->
<script setup>
const [model, modifiers] = defineModel({
  set(value) {
    if (modifiers.capitalize) {
      return value.charAt(0).toUpperCase() + value.slice(1)
    }
    return value
  }
})
</script>

<template>
  <input type="text" v-model="model" />
</template>

vue3官方文档

相关推荐
whinc12 小时前
JavaScript技术周刊 2026年第18周
javascript
码海扬帆:前端探索之旅12 小时前
深度定制 uni-combox:新增功能详解与实战指南
前端·vue.js·uni-app
谷雨不太卷12 小时前
进程的状态码
java·前端·算法
打小就很皮...12 小时前
基于 Python + LangChain + RAG 的知识检索系统实战
前端·langchain·embedding·rag
whinc12 小时前
JavaScript技术周刊 2026年第17周
javascript
BJ-Giser12 小时前
Cesium 烟雾粒子特效
前端·可视化·cesium
空中海12 小时前
02 ArkTS 语言与工程规范
java·前端·spring