我刚刚开始使用 Vue 3 和 Composition API。
我想知道 ref
、 toRef
和 toRefs
之间有什么区别?
最佳答案
Vue 3 ref
ref 是 Vue 3 中的一种 react 机制。 想法是将非对象包装在 reactive
对象中:
Takes an inner value and returns a reactive and mutable ref object. The ref object has a single property
.value
that points to the inner value.
reactive
对于自然对象,不需要 ref 包装,因为它已经是一个对象。它只需要 reactive 功能(ref 也有):const state = reactive({
foo: 1,
bar: 2
})
但是这个对象的属性不是 refs 自然。这意味着如果您要复制一个属性,它将失去与父对象的 react 性/连接。这就是 toRef
有用的地方。toRef
toRef
将单个 reactive
对象属性转换为保持与父对象连接的 ref:const state = reactive({ foo: 1, bar: 2 }) const fooRef = toRef(state, 'foo') /* fooRef: Ref<number>, */
toRefs
toRefs
将所有属性转换为具有 refs 属性的普通对象:const state = reactive({ foo: 1, bar: 2 }) const stateAsRefs = toRefs(state) /* { foo: Ref<number>, bar: Ref<number> } */
关于vue.js - ref、toRef 和 toRefs 之间有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66585688/