注意:ref支持所有的类型数据响应式,但是reactive只支持复杂数据类型,如:Array,Object,Map,Set 等,ref取值赋值操作都需要加.value,而reactive不需要。
import { reactive } from "vue";
const obj = reactive<{ arr: string[] }>({ arr: [] });
const btn = () => {
setTimeout(() => {
let res = ["1", "2", "3"];
obj.arr = res;
}, 500);
};
readonly(只读)
import { reactive, readonly } from "vue";
const obj = reactive<{ arr: string[] }>({ arr: [] });
const copy = readonly(obj);
copy.arr=[] // 会报错,提示不能更改只读属性
// 如果你更改原属性,是可以的(不要这么做这样只读效果失去意义)
obj.arr = ["123"];
shallowReactive(和shallowRef有一样的问题,只能更改浅层数据=>(页面和数据同时更新)),原因是因为对ref的更改会触发重新渲染,而对shallowReactive的更改不会触发重新渲染
import { shallowReactive } from "vue";
const obj = shallowReactive({
arr: {
item: {
name: "钢铁侠",
},
},
});
const btn = () => {
// obj.arr.item.name = "张之维"; // 数据更新但是页面不会更新,下面的方法就可以
obj.arr = {
item: {
name: "张之维",
},
};
};