欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 教育 > 幼教 > vue3.x系列之v-model的使用技巧及面试高频问题

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

2025/5/15 6:05:28 来源:https://blog.csdn.net/qq_27702739/article/details/142779733  浏览:    关键词:vue3.x系列之v-model的使用技巧及面试高频问题

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

组件上面的v-model

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

  • 子组件Child.vue
<!-- 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>
  • 父组件
<Child v-model="count" />

在这里插入图片描述
上面的写法大家应该都很熟悉,应该也会感觉很繁琐。

v3.4版本之后的写法

  • 推荐的实现方式是使用 defineModel() 宏
    修改子组件,父组件保持不变
<!-- 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>
  • 父组件代码
<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保持了联动

自定义我们的输入组件

  • 父组件的
<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>
  • 子组件
<template><p>child msg: {{ inputModel }}</p><input v-model="inputModel" />
</template><script setup>
const inputModel = defineModel();
</script>

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

  • v-model传参
 <MyInput v-model:title="msg" v-model="msg2" />
const msg = ref("abc");
const msg2 = ref("hello");

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

<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>

在这里插入图片描述

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词