Vue 3.5 引入了重要改进,现在可以直接解构 props 而不会失去响应性:
<script setup>
// 直接解构,无需使用 toRefs
const { title, author } = defineProps(['title', 'author'])
// TypeScript 版本
const { title, author } = defineProps<{
title: string
author: string
}>()
</script>
在 Vue 3.5 之前,如果要解构 props 并保持响应性,我们需要使用 toRefs
:
<script setup>
import { toRefs } from 'vue'
// Vue 3.5 之前的写法
const props = defineProps(['title', 'author'])
const { title, author } = toRefs(props)
// 或者直接使用 props.title, props.author
</script>
toRefs
<script setup>
中可用Vue 3.5 的这项改进让 props 的使用变得更加直观和便捷,同时保持了 Vue 的响应式特性。