toRefs()
将响应式对象转换为普通对象,其中结果对象的每个属性都是指向原始对象相应属性的 ref。每个单独的 ref 都是使用创建的toRef()
。
类型
function toRefs<T extends object>( object: T ): { [K in keyof T]: ToRef<T[K]> } type ToRef = T extends Ref ? T : Ref<T>
例子
const state = reactive({ foo: 1, bar: 2 }) const stateAsRefs = toRefs(state) /* Type of stateAsRefs: { foo: Ref<number>, bar: Ref<number> } */ // The ref and the original property is "linked" state.foo++ console.log(stateAsRefs.foo.value) // 2 stateAsRefs.foo.value++ console.log(state.foo) // 3
function useFeatureX() { const state = reactive({ foo: 1, bar: 2 }) // ...logic operating on state // convert to refs when returning return toRefs(state) } // can destructure without losing reactivity const { foo, bar } = useFeatureX()
toRef()
改用。