vue3.4 里面的新特性之v-model实践

vue3.4 里面的新特性

vue 的大版本版本已经升级到 3.4,就在写这篇文章的 30 分钟前,最近新版本是 3.4.20,可见 vue 团队的维护工作一直在持续的进行着...(手动点赞) 那么升级的后的新功能有哪些,这篇文章就来分析下 vue3.4.20 的几个最新功能

v-model

v-model 可以在组件上使用以实现双向绑定。

之前版本的写法

App.vue 组件

html 复制代码
<script setup>
  import Child from "./components/Child.vue";
  import { ref } from "vue";
  const tips = ref(undefined);
</script>

<template>
  <h3>parent:{{ tips }}</h3>
  <Child v-model="tips" />
</template>

<style scoped></style>

Child 组件

html 复制代码
<template>
  <div>
    <h2>{{ msg }}</h2>
    <input v-model="msg" />
  </div>
</template>

<script setup>
  import { ref } from "vue";
  const msg = ref("this is a msg");
</script>
<style scoped></style>

child组件里面的默认值如果要生效,父组件的tips要为undefined,为空null|''会覆盖默认值

  • 正常显示默认值
bash 复制代码
const tips = ref(undefined);
bash 复制代码
const tips = ref("");
  • 不显示默认值

### v3.4 版本的写法

xml 复制代码
从 Vue 3.4 开始,推荐的实现方式是使用 defineModel() 宏:

父组件的没变化,只要是子组件里面有所变化

Child 组件

```html
<template>
  <div>
    <h3>child props:{{ model }}</h3>
    <h3>{{ msg }}</h3>
    <input v-model="msg" />
  </div>
</template>
```

这里需要注意的,父组件的值不能为 null | '',不然子组件的默认值不会显示出来, 赋默认值的方法

bash 复制代码
const model = defineModel({
  default: "this is a default val"
});

此时,我们将 model 赋值给子组件里面的 input 作为响应数据,更新输入框,我们发现父组件的值会同步变化,且控制台没有报错或者警告信息...这样就没有了之前繁琐的 update 更新 emit 事件操作了

组件的多个 v-model

App.vue

html 复制代码
<script setup>
  import Child from "./components/Child.vue";
  import { ref } from "vue";
  const tips = ref(undefined);
  const title = ref("title");
</script>

<template>
  <h3>parent:tips {{ tips }}</h3>
  <h3>parent title:{{ title }}</h3>
  <Child v-model="tips" v-model:title="title" />
</template>

<style scoped></style>

Child.vue

html 复制代码
<template>
  <div>
    <h3>child props:{{ model }}</h3>
    <h3>child props:{{ title }}</h3>
    <h3>{{ title }}</h3>
    <input v-model="title" />
  </div>
</template>

<script setup>
  import { ref } from "vue";

  const msg = ref("this is a msg");
  const model = defineModel({
    default: "this is a default val",
  });

  const title = defineModel("title", { default: "title from parent..." });
</script>
<style lang="less" scoped></style>

经过实战测试,页面正常显示运行,没有显示报错日志

还有更多的特性大家可以自己看官网,对实践其他的新特性

具体参考:cn.vuejs.org/guide/compo...

相关推荐
崔庆才丨静觅5 小时前
hCaptcha 验证码图像识别 API 对接教程
前端
passerby60615 小时前
完成前端时间处理的另一块版图
前端·github·web components
掘了6 小时前
「2025 年终总结」在所有失去的人中,我最怀念我自己
前端·后端·年终总结
崔庆才丨静觅6 小时前
实用免费的 Short URL 短链接 API 对接说明
前端
崔庆才丨静觅6 小时前
5分钟快速搭建 AI 平台并用它赚钱!
前端
崔庆才丨静觅6 小时前
比官方便宜一半以上!Midjourney API 申请及使用
前端
Moment7 小时前
富文本编辑器在 AI 时代为什么这么受欢迎
前端·javascript·后端
崔庆才丨静觅7 小时前
刷屏全网的“nano-banana”API接入指南!0.1元/张量产高清创意图,开发者必藏
前端
剪刀石头布啊7 小时前
jwt介绍
前端
爱敲代码的小鱼7 小时前
AJAX(异步交互的技术来实现从服务端中获取数据):
前端·javascript·ajax