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
  }
})
相关推荐
yatum_20142 分钟前
CentOS 7 集群 SSH 免密与主机名配置文档
linux·前端·网络
014-code9 分钟前
Vue 生命周期完全指南
前端·javascript·vue.js
冴羽yayujs9 分钟前
资深前端都在用的 9 个调试偏方
前端·javascript·调试
Amumu1213812 分钟前
CSS移动端
前端·css·css3
lichenyang45321 分钟前
组件设计模式与通信
前端·javascript·设计模式
im_AMBER37 分钟前
前端性能优化之首屏提速
前端·学习·性能优化
lxh01131 小时前
计算右侧小于当前元素的个数 题解
javascript·数据结构·算法
天天向上10241 小时前
vue 大屏适配的一种实现思路
前端·javascript·vue.js
SuperEugene1 小时前
Vue/Vite 多环境配置实战:dev、test、prod 差异区分与避坑指南|Vue 工程化篇
前端·javascript·vue.js
结网的兔子1 小时前
前端学习笔记(实战准备篇)——用vite构建一个项目【吐血整理】
前端·学习·elementui·npm·node.js·vue