网站首页 > 博客文章 正文
前言
Vue3.5在2024-09-03正式上线,目前在Vue官网显最新版本已经是Vue3.5,其中主要包含了几个小改动,我留意到日常最常用的改动就是props了,肯定是用Vue3的人必用的,所以针对性说一下props的两个小改动使我们日常使用更加灵活。
一、带响应式Props解构赋值
简述: 以前我们对Props直接进行解构赋值是会失去响应式的,需要配合使用toRefs或者toRef解构才会有响应式,那么就多了toRefs或者toRef这工序,而最新Vue3.5版本已经不需要了。
这样直接解构,testCount能直接渲染显示,但会失去响应式,当我们修改testCount时页面不更新。
<template>
<div>
{{ testCount }}
</div>
</template>
<script setup>
import { defineProps } from 'vue';
const props = defineProps({
testCount: {
type: Number,
default: 0,
},
});
const { testCount } = props;
</script>
保留响应式的老写法,使用toRefs或者toRef解构
<template>
<div>
{{ testCount }}
</div>
</template>
<script setup>
import { defineProps, toRef, toRefs } from 'vue';
const props = defineProps({
testCount: {
type: Number,
default: 0,
},
});
const { testCount } = toRefs(props);
// 或者
const testCount = toRef(props, 'testCount');
</script>
最新Vue3.5写法,不借助”外力“直接解构,依然保持响应式
<template>
<div>
{{ testCount }}
</div>
</template>
<script setup>
import { defineProps } from 'vue';
const { testCount } = defineProps({
testCount: {
type: Number,
},
});
</script>
相比以前简洁了真的太多,直接解构使用省去了toRefs或者toRef
二、Props默认值新写法
简述: 以前默认值都是用default: ***去设置,现在不用了,现在只需要解构的时候直接设置默认值,不需要额外处理。
先看看旧的default: ***默认值写法
如下第12就是旧写法,其它以前Vue2也是这样设置默认值
<template>
<div>
{{ props.testCount }}
</div>
</template>
<script setup>
import { defineProps } from 'vue';
const props = defineProps({
testCount: {
type: Number,
default: 1
},
});
</script>
最新优化的写法 如下第9行,解构的时候直接一步到位设置默认值,更接近js语法的写法。
<template>
<div>
{{ testCount }}
</div>
</template>
<script setup>
import { defineProps } from 'vue';
const { testCount=18 } = defineProps({
testCount: {
type: Number,
},
});
</script>
小结
这次更新其实props的本质功能并没有改变,但写法确实变的更加丝滑好用了,props使用非常高频感觉还是有必要跟进这种更简洁的写法。如果那里写的不对或者有更好建议欢迎大佬指点啊。
- 上一篇: vue.js中mounted
- 下一篇: 怎么在 vue 中使用 form 清除校验状态?
猜你喜欢
- 2025-05-24 Vue3开发极简入门(12):params传参&props传参
- 2025-05-24 10个实例小练习,快速入门熟练 Vue3 核心新特性(一)
- 2025-05-24 怎么在 vue 中使用 form 清除校验状态?
- 2025-05-24 vue.js中mounted
- 2025-05-24 11、Refs:直接操控元素——React 19 DOM操作秘籍
- 2025-05-24 Vue3 响应式编程:深度剖析 ref 与 reactive 的正确打开方式
- 2025-05-24 vue3中到底使用Ref还是Reactive,我和同事吵起来了
你 发表评论:
欢迎- 379℃手把手教程「JavaWeb」优雅的SpringMvc+Mybatis整合之路
- 373℃用AI Agent治理微服务的复杂性问题|QCon
- 364℃IT全明星|IntelliJ IDEA学习笔记(四、idea中怎么创建maven项目)
- 364℃初次使用IntelliJ IDEA新建Maven项目
- 358℃Maven技术方案最全手册(mavena)
- 355℃安利Touch Bar 专属应用,让闲置的Touch Bar活跃起来!
- 352℃InfoQ 2024 年趋势报告:架构篇(infoq+2024+年趋势报告:架构篇分析)
- 352℃IntelliJ IDEA 2018版本和2022版本创建 Maven 项目对比
- 最近发表
- 标签列表
-
- powershellfor (55)
- messagesource (56)
- aspose.pdf破解版 (56)
- promise.race (63)
- 2019cad序列号和密钥激活码 (62)
- window.performance (66)
- qt删除文件夹 (72)
- mysqlcaching_sha2_password (64)
- ubuntu升级gcc (58)
- nacos启动失败 (64)
- ssh-add (70)
- jwt漏洞 (58)
- macos14下载 (58)
- yarnnode (62)
- abstractqueuedsynchronizer (64)
- source~/.bashrc没有那个文件或目录 (65)
- springboot整合activiti工作流 (70)
- jmeter插件下载 (61)
- 抓包分析 (60)
- idea创建mavenweb项目 (65)
- vue回到顶部 (57)
- qcombobox样式表 (68)
- vue数组concat (56)
- tomcatundertow (58)
- pastemac (61)
本文暂时没有评论,来添加一个吧(●'◡'●)