原文 Weekly Vue News #80 - Destructure Props in Composition API Without Losing Reactivity
在 <script setup> 中,我们使用 defineProps() 这个编译器宏来访问 props 。
<script setup lang="ts">
const props = defineProps<{ count: number }>()
</script>
同时,我们很喜欢在 JavaScript 使用对象解构,我们可以尝试一下解构 props。
<script setup lang="ts">
const { count } = defineProps<{ count: number }>()
</script>
当我们直接解构 props 时,响应会丢失!
对 props 对象进行解构,得到的 count 会变成一个原始对象(在我们这个例子中,它的类型是 number),不再是一个 ref 或 reactive 响应式对象。
为了保留响应式,最简便的办法是通过 props.count 进行数据访问。
<script setup lang="ts">
import { computed } from 'vue'
const props = defineProps<{ count: number }>()
const doubleCount = computed(() => props.count * 2) // <-----
</script>
<template>Double Count: {{ doubleCount }}</template>
如果你一定要使用解构,那么可以使用 Vue 提供的一个工具 toRefs。
<script setup lang="ts">
import { computed, toRefs } from 'vue'
const props = defineProps<{ name: string }>()
const { count } = toRefs(props) // <-----
const doubleCount = computed(() => count.value * 2)
</script>
<template>Double Count: {{ doubleCount }}</template>
通过 toRefs(props) ,props 会变成一个普通对象,但是其所有的属性都变成原始属性的响应式引用。因此,我们在 computed 中,需要使用 name.value 的格式来获取数据,因为解构出来的对象是一个 ref 对象。
点击访问 示例