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
  }
})
相关推荐
阿捞28 分钟前
Inertia.js 持久布局实现原理
前端·javascript·html
不会写DN10 分钟前
如何在纯前端中通过手势交互来控制星球的转动
前端·交互
w2sfot10 分钟前
反AI逆向JS加密
javascript·人工智能·反ai
liliangcsdn30 分钟前
sentence-transformer如何离线加载和使用模型
开发语言·前端·php
东宇科技1 小时前
如何使用js进行抠图。识别商品主体
开发语言·javascript·ecmascript
不会写DN1 小时前
Vue3中的computed 与 watch 的区别
javascript·面试·vue
qq_381338501 小时前
TypeScript 类型安全与类型体操实战:从入门到精通
javascript·安全·typescript
朦胧之1 小时前
AI 编程工具使用浅谈
前端·后端
柳杉1 小时前
HTML-in-Canvas:让 Canvas 完美渲染 HTML 的 Web 新标准
前端·javascript