Vue3.5 发布已近半年,抽空整理下常用的新增/改动特性
响应式 Props 解构
Vue3.5 中 Props 正式支持解构了,并添加了响应式跟踪
设置默认值
使用 JavaScript 原生的默认值语法声明 props 默认值
以前
const props = withDefaults(
defineProps<{
count?: number
msg?: string
}>(),
{
count: 0,
msg: 'hello'
}
)
现在
const { count = 0, msg = 'hello' } = defineProps<{
count?: number
message?: string
}>()
响应式解构
当在同一个 <script setup> 代码块中访问由 defineProps 解构的变量时,Vue 编译器会自动在前面添加 props
以前
const { foo } = defineProps(['foo'])
watchEffect(() => {
// 在 3.5 之前只运行一次
console.log(foo)
})
现在
const { foo } = defineProps(['foo'])
watchEffect(() => {
// 在 3.5 中在 "foo" prop 变化时重新执行
console.log(foo)
// `foo` 由编译器转换为 `props.foo`,以上等同于 `console.log(props.foo)`
})
与之类似,监听解构的 prop 变量 或 将其传递到可组合项中同时保留响应性 时需要将其包