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
  }
})
相关推荐
lyj16899712 分钟前
vue-i18n+vscode+vue 多语言使用
前端·vue.js·vscode
小白变怪兽2 小时前
一、react18+项目初始化(vite)
前端·react.js
ai小鬼头2 小时前
AIStarter如何快速部署Stable Diffusion?**新手也能轻松上手的AI绘图
前端·后端·github
墨菲安全3 小时前
NPM组件 betsson 等窃取主机敏感信息
前端·npm·node.js·软件供应链安全·主机信息窃取·npm组件投毒
GISer_Jing3 小时前
Monorepo+Pnpm+Turborepo
前端·javascript·ecmascript
天涯学馆3 小时前
前端开发也能用 WebAssembly?这些场景超实用!
前端·javascript·面试
我在北京coding4 小时前
TypeError: Cannot read properties of undefined (reading ‘queryComponents‘)
前端·javascript·vue.js
前端开发与ui设计的老司机4 小时前
UI前端与数字孪生结合实践探索:智慧物流的货物追踪与配送优化
前端·ui
全能打工人4 小时前
前端查询条件加密传输方案(SM2加解密)
前端·sm2前端加密