返回
创建于
状态公开

VueUse toReactive 正确用法

在 Vue 组合式 API 中,refreactive 常常混用。当我们把多个 ref 聚合到一个对象里时,直接使用会出现大量 .value,这时可以使用 VueUse 提供的 toReactive 工具方法。


基本用法

ts
1import { ref } from 'vue'
2import { toReactive } from '@vueuse/core'
3
4const count = ref(0)
5const msg = ref('hello')
6
7const state = { count, msg }
8const reactiveState = toReactive(state)
9
10// 直接访问,不需要 .value
11console.log(reactiveState.count) // 0
12console.log(reactiveState.msg)   // 'hello'
13
14// 修改也会同步回原始 ref
15reactiveState.count++
16console.log(count.value) // 1

常见场景

将一组 ref 打包

ts
1const x = ref(10)
2const y = ref(20)
3
4const coords = { x, y }
5const reactiveCoords = toReactive(coords)
6
7// 模板中直接使用 reactiveCoords.x / reactiveCoords.y

与解构结合

ts
1const foo = ref('foo')
2const bar = ref('bar')
3
4const obj = toReactive({ foo, bar })
5const { foo: f, bar: b } = obj
6
7console.log(f, b) // 自动响应式

错误用法

⚠️ toReactive 并不是把单个 ref 转成响应式对象的工具。

ts
1const a = ref({ type: 'img' })
2
3// ❌ 这样写没有意义
4const wrong = toReactive(a)

如果只有一个 ref,直接用就行,或者用 toRef 取子字段:

ts
1const overlayInfo = ref({ watermark: { type: 'img' } })
2const watermarkRef = toRef(overlayInfo.value, 'watermark')
3
4// 正确使用
5watermarkRef.value.type = 'video'

总结

  • 适用场景:对象里都是 ref,想批量解包成 reactive,避免 .value
  • 不适用场景:只有单个 ref,或者对象里不是 ref
  • 替代方案:单个 reftoRef,模板里用 Vue 自动解包,或者用 computed 包装。