You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue3 script setup语法下toRefs的使用方式及必要性咨询

在Vue的script setup中使用toRefs的正确方式

核心结论

在script setup语法中,不是必须要用toRefs,要不要用完全取决于你的使用场景:

1. 不需要解构state属性时:直接用reactive对象即可

script setup里的顶层变量会自动暴露给模板,所以如果你的模板是通过state.xxx的方式访问属性,完全不需要toRefs,直接用reactive创建的对象就行:

<script setup>
import { reactive } from 'vue'

const state = reactive({
  count: 0,
  username: 'test'
})
</script>

<template>
  <div>计数:{{ state.count }}</div>
  <div>用户名:{{ state.username }}</div>
</template>

2. 需要单独解构state属性时:用toRefs保持响应式

如果你想把reactive对象里的属性单独解构出来使用(比如在script里频繁调用,或者模板里不想写state.前缀),就需要用toRefs把reactive对象转成ref对象集合,这样解构后的每个属性依然保持响应式:

<script setup>
import { reactive, toRefs } from 'vue'

const state = reactive({
  count: 0,
  username: 'test'
})

// 解构后count和username都是ref对象,自动暴露给模板
const { count, username } = toRefs(state)

// 在script里需要用.value访问
count.value++
</script>

<template>
  <div>计数:{{ count }}</div> <!-- 模板自动解包ref,不用写.value -->
  <div>用户名:{{ username }}</div>
</template>

3. 处理props时的toRefs用法

defineProps返回的是一个响应式的proxy对象,和reactive逻辑一致:

  • 如果直接用props.header访问,不需要toRefs
  • 如果要解构props的属性,必须用toRefs,否则会丢失响应式:
<script setup>
import { toRefs } from 'vue'

const props = defineProps({
  header: String
})

// 解构header为ref对象,保持响应式
const { header } = toRefs(props)
</script>

<template>
  <div>{{ header }}</div>
</template>

和旧写法的区别

之前选项式API的setup函数里,需要通过return { ...toRefs(state) }把属性单独暴露给模板;而script setup会自动暴露顶层变量,所以只要把解构后的ref变量放在顶层,模板就能直接用,不需要手动return。

内容的提问来源于stack exchange,提问作者User123123

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 23:01:09