大成设计网站建设,什么是移动网站开发,中山seo代理计费,wordpress微信登录开发文档Vue 3 的 reactive 是创建响应式对象的核心 API#xff0c;但在使用过程中有一些需要注意的事项#xff1a;
1#xff1a;基本使用限制 仅对对象类型有效#xff1a;reactive 只能用于对象类型#xff08;Object、Array、Map、Set 等#xff09;#xff0c;不能用于原始…Vue 3 的 reactive 是创建响应式对象的核心 API但在使用过程中有一些需要注意的事项
1基本使用限制 仅对对象类型有效reactive 只能用于对象类型Object、Array、Map、Set 等不能用于原始值string、number、boolean 等
const state reactive({ count: 0 }) // 正确
const count reactive(0) // 不会生效2响应式丢失问题 解构会失去响应性直接解构 reactive 对象会导致响应性丢失
const state reactive({ count: 0 })
let { count } state // count 不再是响应式的// 解决方案使用 toRefs
const { count } toRefs(state) // 保持响应性直接赋值会失去响应性将 reactive 对象整体赋值给另一个变量会失去响应性
const state reactive({ count: 0 })
let copy state // copy 不会触发视图更新3数组和集合类型的注意事项 数组的特殊情况直接通过索引修改数组元素或修改 length 属性不会触发响应
const arr reactive([1, 2, 3])
arr[0] 9 // 不会触发响应// 解决方案
arr.splice(0, 1, 9) // 使用数组方法
// 或使用 ref 包裹数组Map/Set 的使用需要使用方法修改而不是直接赋值
const map reactive(new Map())
map.set(key, value) // 正确
map[key] value // 不会触发响应4性能考虑 深层响应式reactive 是深层的所有嵌套属性都是响应式的对于大型对象可能有性能影响
const obj reactive({nested: {deep: {value: 1 // 所有层级都是响应式的}}
})浅层响应式如果需要浅层响应式可以使用 shallowReactive
5其他注意事项 避免重复包装不要对已经是 reactive 的对象再次调用 reactive
const state reactive({ count: 0 })
const doubleWrapped reactive(state) // 不必要的与 ref 的互操作reactive 会自动解包 ref 对象
const count ref(0)
const state reactive({ count })
console.log(state.count) // 直接访问不需要 .value响应式对象替换替换整个 reactive 对象不会保持响应性
let state reactive({ count: 0 })
state reactive({ count: 1 }) // 错误的做法// 正确做法是修改属性
Object.assign(state, { count: 1 })