Vue3.4 中自定义组件 v-model 双向数据绑定

父组件如下:

虽然下面userName没有使用 v-model.userName="userName"的写法,它默认与子组件中 defineModel();中不指定参数的变量对应,

只能有一个不指定名称,否则会报如下错

bash 复制代码
<template>
  <div>
    {{ userName}}- {{ age}}- {{ sex }}
    <!-- 自定义子组件 PersonalInformation 使用 v-model 指令绑定 userName -->
    <PersonalInformation
      v-model="userName"
      v-model:age="age"
      v-model:sex ="sex "
    />
  </div>
</template>

<script setup>
import { ref } from "vue";
import PersonalInformationfrom './PersonalInformation.vue'

const userName = ref("张三");
const age= ref(25);
const sex = ref("男");
</script>

子组件(PersonalInformationfrom )

bash 复制代码
<!-- 子组件 PersonalInformationfrom -->
<template>
  <input type="text" v-model="userName_ext " />
  <input type="number" v-model="age_ext" />
  <input type="text" v-model="sex_ext" />
  <button @click="btn">测试</button>
</template>

<script setup>
	const userName_ext = defineModel();
	const age_ext= defineModel("age");
	const sex_ext= defineModel("sex");
	function btn(){
	  console.log("age",age.value);
	  age.value=100;
	}
</script>

标题修饰符和转换器

为了获取 v-model 指令使用的修饰符,我们可以像这样解构 defineModel() 的返回值:

js 复制代码
const [userName, age,sex] = defineModel()

// 对应 v-model.trim
if (age.trim) {
  // ...
}

我们可能需要在读取或将其同步回父组件时对其值进行修改转换。我们使用 get 和 set 转换器选项来实现这一点:

bash 复制代码
const [userName, age,sex] = defineModel({
  // get() 省略了,因为这里不需要它
  set(value) {
    // 使用 .trim 修饰符过滤用户输入的首尾空格,返回过滤后的值
    if (age.trim) {
      return value.trim()
    }
    // 否则,原样返回
    return value
  }
})
相关推荐
顾安r26 分钟前
11.14 脚本网页 青蛙过河
服务器·前端·python·游戏·html
阿奇__36 分钟前
el-table有固定列时样式bug
vue.js·elementui·bug
LXA08091 小时前
在Vue 3项目中配置和使用SCSS
vue.js·rust·scss
不爱吃糖的程序媛1 小时前
Electron 智能文件分析器开发实战适配鸿蒙
前端·javascript·electron
Doro再努力1 小时前
2025_11_14洛谷【入门1】数据结构刷题小结
前端·数据结构·算法
IT_陈寒1 小时前
SpringBoot 3.2新特性实战:这5个隐藏技巧让你的应用性能飙升50%
前端·人工智能·后端
flashlight_hi1 小时前
LeetCode 分类刷题:3217. 从链表中移除在数组中存在的节点
javascript·数据结构·leetcode·链表
Java追光着1 小时前
React Native 自建 JS Bundle OTA 更新系统:从零到一的完整实现与踩坑记录
javascript·react native·react.js
努力往上爬de蜗牛1 小时前
react native 运行问题和调试 --持续更新
javascript·react native·react.js
eason_fan2 小时前
Monorepo性能噩梦:一行配置解决VSCode卡顿与TS类型崩溃
前端·typescript·visual studio code