toRef()
可用于为源响应对象上的属性创建 ref。创建的 ref 与其源属性同步:改变源属性将更新 ref,反之亦然。
类型
function toRef<T extends object, K extends keyof T>( object: T, key: K, defaultValue?: T[K] ): ToRef<T[K]> type ToRef<T> = T extends Ref ? T : Ref<T>
例子
const state = reactive({ foo: 1, bar: 2 }) const fooRef = toRef(state, 'foo') // mutating the ref updates the original fooRef.value++ console.log(state.foo) // 2 // mutating the original also updates the ref state.foo++ console.log(fooRef.value) // 3
请注意,这不同于:
const fooRef = ref(state.foo)
上面的 ref 没有与 state.foo 同步,因为ref()
接收一个纯字符串值。
toRef()
当您想将 prop 的 ref 传递给可组合函数时很有用:
<script setup> const props = defineProps(/* ... */) // convert `props.foo` into a ref, then pass into // a composable useSomeFeature(toRef(props, 'foo')) </script>
toRef()
即使源属性当前不存在,也会返回一个可用的引用。这使得它在使用可选道具时特别有用,这些道具不会被 toRefs.