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