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

相关推荐
猿饵块31 分钟前
cmake--get_filename_component
java·前端·c++
大表哥642 分钟前
在react中 使用redux
前端·react.js·前端框架
十月ooOO1 小时前
【解决】chrome 谷歌浏览器,鼠标点击任何区域都是 Input 输入框的状态,能看到输入的光标
前端·chrome·计算机外设
qq_339191141 小时前
spring boot admin集成,springboot2.x集成监控
java·前端·spring boot
pan_junbiao1 小时前
Vue使用代理方式解决跨域问题
前端·javascript·vue.js
明天…ling1 小时前
Web前端开发
前端·css·网络·前端框架·html·web
ROCKY_8171 小时前
web前端-HTML常用标签-综合案例
前端·html
海石1 小时前
从0到1搭建一个属于自己的工作流站点——羽翼渐丰(bpmn-js、Next.js)
前端·javascript·源码
Q186000000001 小时前
在HTML中添加图片
前端·html
傻虎贼头贼脑2 小时前
day21JS-npm中的部分插件使用方法
前端·npm·node.js