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
  }
})
相关推荐
大怪v5 小时前
AI抢饭?前端佬:我要验牌!
前端·人工智能·程序员
新酱爱学习5 小时前
字节外包一年,我的技术成长之路
前端·程序员·年终总结
小兵张健6 小时前
开源 playwright-pool 会话池来了
前端·javascript·github
IT_陈寒8 小时前
Python开发者必知的5大性能陷阱:90%的人都踩过的坑!
前端·人工智能·后端
codingWhat9 小时前
介绍一个手势识别库——AlloyFinger
前端·javascript·vue.js
Lee川9 小时前
深度拆解:基于面向对象思维的“就地编辑”组件全模块解析
javascript·架构
勤劳打代码9 小时前
Flutter 架构日记 — 状态管理
flutter·架构·前端框架
代码老中医9 小时前
2026年CSS彻底疯了:这6个新特性让我删掉了三分之一JS代码
前端
进击的尘埃9 小时前
Web Worker 与 OffscreenCanvas:把主线程从重活里解放出来
javascript
不会敲代码19 小时前
Zustand:轻量级状态管理,从入门到实践
前端·typescript