当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Vue.js 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)

上面的参考是不是同步state.foo,因为ref()接收一个普通的数字值。

toRef() 当您想将 prop 的 ref 传递给可组合函数时很有用:

<script setup>
import { toRef } from 'vue'

const props = defineProps(/* ... */)

// convert `props.foo` into a ref, then pass into
// a composable
useSomeFeature(toRef(props, 'foo'))
</script>

什么时候toRef与组件 props 一起使用时,关于改变 props 的通常限制仍然适用。尝试为 ref 分配新值相当于尝试直接修改 prop,并且是不允许的。在这种情况下,您可能需要考虑使用computed()getset反而。请参阅指南v-model 与组件一起使用了解更多信息。

toRef() 将返回一个可用的引用,即使源属性当前不存在。这使得使用可选属性成为可能,这些属性不会被 toRefs 拾取。

相关用法


注:本文由纯净天空筛选整理自vuejs.org大神的英文原创作品 toRef()。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。