Skip to content

toRef

类别
导出大小
180 B
最近修改
2 days ago
别名
resolveRef

将 value/ref/getter 标准化为 refcomputed

🌐 Normalize value/ref/getter to ref or computed.

用法

🌐 Usage

ts
import { 
toRef
} from '@vueuse/core'
const
foo
=
ref
('hi')
const
a
=
toRef
(0) // Ref<number>
const
b
=
toRef
(
foo
) // Ref<string>
const
c
=
toRef
(() => 'hi') // ComputedRef<string>

与 Vue 的 toRef 的区别

🌐 Differences from Vue's toRef

VueUse 的 toRef 与 Vue 的 vue 包中的 toRef 不同。

🌐 VueUse's toRef is not the same as Vue’s toRef from the vue package.

VueUse toRef

  • 接受 valuerefgetter
  • 返回值:
    • 原始值的 引用
    • 现有引用的 ref
    • 用于 getter 函数的 computed
  • 不接受 object + key
  • getter 始终生成只读的计算值

Vue toRef

  • 仅接受:
    • 一个 响应式对象 + 属性键,或者
    • 一个现有的 ref
  • 生成一个与底层响应式对象关联的可写 ref
  • 不接受原始值
  • 不接受 getter 函数

总结

🌐 Summary

行为VueUse toRefVue toRef
接受原始值✔️
接受 getter✔️ (computed)
接受已有的 ref✔️✔️
接受对象 + key✔️
可写✔️ (除 getter 外)✔️
目的标准化为 ref/computed绑定到响应式对象