logo
火山博客
导航

Vue 3.5 父组件向子组件传值:Props 新特性详解

2025-02-11
7阅读时间2分钟

Props 解构增强

Vue 3.5 引入了重要改进,现在可以直接解构 props 而不会失去响应性:

Javascript
<script setup>
// 直接解构,无需使用 toRefs
const { title, author } = defineProps(['title', 'author'])

// TypeScript 版本
const { title, author } = defineProps<{
  title: string
  author: string
}>()
</script>

与旧版本对比

在 Vue 3.5 之前,如果要解构 props 并保持响应性,我们需要使用 toRefs

Javascript
<script setup>
import { toRefs } from 'vue'

// Vue 3.5 之前的写法
const props = defineProps(['title', 'author'])
const { title, author } = toRefs(props)

// 或者直接使用 props.title, props.author
</script>

新特性优势

  1. 更简洁的语法:无需引入和使用 toRefs
  2. 更好的开发体验:直接解构即可保持响应性
  3. 更少的运行时开销:不需要创建额外的 ref 对象

注意事项

  • 这个特性仅在 <script setup> 中可用
  • 解构后的属性仍然是只读的,遵循 Vue 的单向数据流原则
  • 如果需要修改 prop 值,仍然建议使用计算属性或本地状态

Vue 3.5 的这项改进让 props 的使用变得更加直观和便捷,同时保持了 Vue 的响应式特性。

2024 © Powered by
hsBlog
|
后台管理