reactive
用来绑定复杂的数据类型 例如 对象 数组
Aarry Object set map
reactive 源码约束了我们的类型<T extends object>
他是不可以绑定普通的数据类型
这样是不允许 会给我们报错
import { reactive} from 'vue'
let person = reactive('sad')
绑定普通的数据类型 我们可以 使用ref
你如果用ref去绑定对象 或者 数组 等复杂的数据类型 我们看源码里面其实也是 去调用reactive
使用reactive 去修改值无须.value
import { reactive } from 'vue'
let person = reactive({
name:"小"
})
person.name = "大"
let n = reactive({ name: "cookie" }); // reactive本身会做个类型推断
type M = {
name: string;
};
let n1 = reactive<M>({ name: "cookie" }); //若推到不出可自定义
数组异步赋值问题
这样赋值页面是不会变化的因为会脱离响应式
reactive([]) 是个proxy不能直接赋值 否则会破坏响应式对象的
let person = reactive<number[]>([])
setTimeout(() => {
person = [1, 2, 3]
console.log(person);
},1000)
解决方案1push+解构
import { reactive } from 'vue'
let person = reactive<number[]>([])
setTimeout(() => {
const arr = [1, 2, 3]
person.push(...arr)
console.log(person);
},1000)
解决方案2.添加一个对象 把数组作为一个属性去解决
type Person = {
list?:Array<number>
}
let person = reactive<Person>({
list:[]
})
setTimeout(() => {
const arr = [1, 2, 3]
person.list = arr;
console.log(person);
},1000)
完整代码
<template>
<ul>
<li v-for="key in list" :key="key">{{ key }}</li>
<li v-for="key in list1.arr" :key="key">{{ key }}</li>
<button @click="add">添加li</button>
</ul>
<hr />
<button @click="show">showReadOnly</button>
</template>
<script setup lang="ts">
import {
ref,
reactive,
readonly,
ShallowReactive,
shallowRef,
} from "vue";
let list: string[] = reactive([]);
let list1 = reactive<{ arr: string[] }>({ arr: [] });
const add = () => {
setTimeout(() => {
let res = ["a", "b"];
// list = res; //是个proxy不能直接赋值 否则会破坏响应式对象的
list.push(...res);
list1.arr = res;
console.log(list);
}, 500);
};
</script>
readonly
let s = reactive({ name: "cookie" });
let s1 = readonly(s); //源码中使用的多
const show = () => {
// s1.name = 's' // 只读不能修改
s.name = "s"; // 修改原始对象会被修改了。。
console.log(s, s1);
};
shallowReactive
只能对浅层的数据 如果是深层的数据只会改变值 不会改变视图 同shallowRef一样