返回对象的反应式代理。
类型
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()。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。