可用于为源响应对象上的属性创建 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()和get
和set
反而。请参阅指南将v-model
与组件一起使用了解更多信息。
toRef()
将返回一个可用的引用,即使源属性当前不存在。这使得使用可选属性成为可能,这些属性不会被
拾取。toRefs
相关用法
- Vue.js toRefs()用法及代码示例
- Vue.js toRaw()用法及代码示例
- Vue.js triggerRef()用法及代码示例
- Vue.js useSSRContext()用法及代码示例
- Vue.js app.directive()用法及代码示例
- Vue.js mergeProps()用法及代码示例
- Vue.js app.config.warnHandler用法及代码示例
- Vue.js pipeToWebWritable()用法及代码示例
- Vue.js app.use()用法及代码示例
- Vue.js v-pre用法及代码示例
- Vue.js h()用法及代码示例
- Vue.js serverPrefetch用法及代码示例
- Vue.js customRef()用法及代码示例
- Vue.js <Transition>用法及代码示例
- Vue.js inject()用法及代码示例
- Vue.js mixins用法及代码示例
- Vue.js ComponentCustomProps用法及代码示例
- Vue.js reactive()用法及代码示例
- Vue.js ComponentCustomProperties用法及代码示例
- Vue.js app.mount()用法及代码示例
- Vue.js <component>用法及代码示例
- Vue.js createRenderer()用法及代码示例
- Vue.js onMounted()用法及代码示例
- Vue.js createApp()用法及代码示例
- Vue.js app.config.errorHandler用法及代码示例
注:本文由纯净天空筛选整理自vuejs.org大神的英文原创作品 toRef()。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。