vue3.x系列之v-model的使用技巧及面试高频问题

在前面的一篇文章中,我们分析了v-model在v2版中的用法。这次我们分析下在v3中的使用技巧。学习之前,请忘记之前的v2语法,现在的更加简洁易用。

组件上面的v-model

在v3.4版之前的写法如下

  • 子组件Child.vue
js 复制代码
<!-- Child.vue -->
<script setup>
defineProps({
  modelValue: {
    type: Number,
    default: 0
  }
});

const emits = defineEmits(["update"]);
//function update() {
//  emits("update:modelValue", modelValue + 1);
//}
</script>

<template>
  <div>Parent bound v-model is: {{ modelValue }}</div>
  <button @click="$emit('update:modelValue',modelValue + 2)">Increment</button>
</template>
  • 父组件
html 复制代码
<Child v-model="count" />


上面的写法大家应该都很熟悉,应该也会感觉很繁琐。

v3.4版本之后的写法

  • 推荐的实现方式是使用 defineModel() 宏
    修改子组件,父组件保持不变
js 复制代码
<!-- Child.vue -->
<script setup>
const model = defineModel();
function update() {
  model.value++;
}
</script>

<template>
  <div>Parent bound v-model is: {{ model }}</div>
  <button @click="update">Increment</button>
</template>
  • 父组件代码
js 复制代码
<template>
  <div>
    <h1>VModelView</h1>
    <p>parent count: {{ count }}</p>
    <Child v-model="count" />
  </div>
</template>

<script setup>
import Child from "@/components/Child.vue";
import { ref } from "vue";
const count = ref(0);
</script>

可以观察到,实现了一样的效果,代码也简洁了很多。

defineModel() 返回的值是一个 ref。它可以像其他 ref 一样被访问以及修改,不过它能起到在父组件和当前变量之间的双向绑定的作用

  • 在子组件中直接更改了这个model的value值,
  • 父组件中的count与组件中的model.value保持了联动

自定义我们的输入组件

  • 父组件的
js 复制代码
<template>
  <div>
    <h1>VModelView</h1>
    <p>parent count: {{ count }}</p>
    <Child v-model="count" />
    <br />
    <p>parent msg:{{ msg }}</p>
    <MyInput v-model="msg" />
  </div>
</template>

<script setup>
import Child from "@/components/Child.vue";
import MyInput from "@/components/MyInput.vue";
import { ref } from "vue";
const count = ref(0);
const msg = ref("hello world");
</script>
  • 子组件
js 复制代码
<template>
  <p>child msg: {{ inputModel }}</p>
  <input v-model="inputModel" />
</template>

<script setup>
const inputModel = defineModel();
</script>

这样我们就很简洁的封装了一个自定义的单行文本组件,自己加点样式美化即可。

  • v-model传参
html 复制代码
 <MyInput v-model:title="msg" v-model="msg2" />
js 复制代码
const msg = ref("abc");
const msg2 = ref("hello");

子组件中defineModel必须接收这个参数,否则不会显示对应的数据,无参可以不用传。

html 复制代码
<template>
  <p>child msg: {{ inputModel }}</p>
  <input v-model="inputModel" />
  <br />
  <input v-model="inputModel2" />
</template>

<script setup>
const inputModel = defineModel("title");
const inputModel2 = defineModel();
</script>
相关推荐
我是伪码农4 小时前
Vue 智慧商城项目
前端·javascript·vue.js
不认输的西瓜4 小时前
fetch-event-source源码解读
前端·javascript
用户39051332192884 小时前
前端性能杀手竟然不是JS?图片优化才是绝大多数人忽略的"降本增效"方案
前端
朱昆鹏5 小时前
开源 Claude Code + Codex + 面板 的未来vibecoding平台
前端·后端·github
lyrieek5 小时前
pgadmin的导出图实现,还在搞先美容后拍照再恢复?
前端
小书包酱5 小时前
在 VS Code中,vue2-vuex 使用终于有体验感增强的插件了。
vue.js·vuex
永远是我的最爱5 小时前
基于.NET的小小便利店前台收银系统
前端·sqlserver·.net·visual studio
从文处安5 小时前
「九九八十一难」第一难:前端数据mock指南(TS + VUE)
前端
Zhencode5 小时前
Vue3 响应式依赖收集与更新之effect
前端·vue.js
x-cmd5 小时前
[x-cmd] jsoup 1.22.1 版本发布,引入 re2j 引擎,让 HTML 解析更安全高效
前端·安全·html·x-cmd·jsoup