返回對象的反應式代理。
類型
function reactive<T extends object>(target: T): UnwrapNestedRefs<T>
細節
反應轉換是"deep":它影響所有嵌套屬性。反應性對象還可以深入解包 refs 的任何屬性,同時保持反應性。
還應該注意的是,當引用作為反應數組的元素或本機集合類型(如 Map
)訪問時,不會執行引用解包。
為避免深度轉換並僅在根級別保留反應性,請改用shallowReactive()。
返回的對象及其嵌套對象用ES 代理和不是等於原始對象。建議隻使用響應式代理並避免依賴原始對象。
示例
創建一個反應對象:
const obj = reactive({ count: 0 })
obj.count++
參考展開:
const count = ref(1)
const obj = reactive({ count })
// ref will be unwrapped
console.log(obj.count === count.value) // true
// it will update `obj.count`
count.value++
console.log(count.value) // 2
console.log(obj.count) // 2
// it will also update `count` ref
obj.count++
console.log(obj.count) // 3
console.log(count.value) // 3
請注意,參考是不是當作為數組或集合元素訪問時展開:
const books = reactive([ref('Vue 3 Guide')])
// need .value here
console.log(books[0].value)
const map = reactive(new Map([['count', ref(0)]]))
// need .value here
console.log(map.get('count').value)
將 ref 分配給 reactive
屬性時,該引用也將自動展開:
const count = ref(1)
const obj = reactive({})
obj.count = count
console.log(obj.count) // 1
console.log(obj.count === count.value) // true
相關用法
- Vue.js readonly()用法及代碼示例
- Vue.js ref()用法及代碼示例
- Vue.js renderToSimpleStream()用法及代碼示例
- Vue.js renderToNodeStream()用法及代碼示例
- Vue.js renderToString()用法及代碼示例
- Vue.js resolveComponent()用法及代碼示例
- Vue.js renderToWebStream()用法及代碼示例
- 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 ComponentCustomProperties用法及代碼示例
- Vue.js app.mount()用法及代碼示例
- Vue.js <component>用法及代碼示例
- Vue.js createRenderer()用法及代碼示例
注:本文由純淨天空篩選整理自vuejs.org大神的英文原創作品 reactive()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。