vue3新增了响应性API,其中数据有两种,ref
和reactive
。
reactive
支持非原始对象,基础类型不能使用(Number,Boolean
等)
例1
const obj = reactive({ count: 0 })
obj.count++
console.log(obj.count) // 1
const obj = reactive([])
obj.push(1)
console.log(obj) // [1]
注意:使用
let
定义后不能直接重新赋值reactive对象,会导致响应式的代理被覆盖。
例2
export default {
name: 'App',
setup() {
let obj = reactive({a:1})
// 不能这么写,这样重新赋值后会,obj会变成普通对象,失去响应式的效果;
setTimeout(() => {
obj = {a:2,b:3}
}, 1000)
return {
obj
}
}
}
遇到这样的情况,需要单独赋值
例3
const obj = reactive({a:1})
setTimeout(() => {
obj.a = 2;
obj.b = 3;
}, 1000)
或者使用Object.assign
例4
export default {
name: 'App',
setup() {
const obj = reactive({a:1})
setTimeout(() => {
Object.assign(obj,{a:2, b:3})
}, 1000)
return {
obj
}
}
}
网友评论