在 Vue 中, toRefs(state) 的返回值是一个 新对象,其中每个属性都是对应 state 中原始属性的 ref 对象。具体来说:
返回值的结构与特性
1. 对象结构
- 若输入 state 为 { a: 1, b: 'text' } ,则 toRefs(state) 返回:
{
a: ref(1), // ref 对象,值为 state.a
b: ref('text') // ref 对象,值为 state.b
}
2. 核心特性
- 双向绑定:返回的 ref 对象与原始 state 属性双向关联,修改任意一方都会同步更新另一方:
const state = reactive({ count: 0 });
const refs = toRefs(state);
refs.count.value = 10; // state.count 变为 10
state.count = 20; // refs.count.value 变为 20
- 保持响应式:当通过 toRefs 解构返回值时, ref 对象的响应式特性不会丢失:
const { count } = toRefs(state);
// 后续修改 count.value 会触发视图更新
总结
toRefs(state) 的返回值是一个 包含多个 ref 对象的新对象,每个 ref 对应 state 的一个属性,并与原始属性双向绑定,主要用于在解构响应式对象时保持其响应式特性。