可用於為源響應對象上的屬性創建 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()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。