《Vue3中的Reactive》

绑定普通的数据类型 我们可以使用 ref

你如果用 ref 去绑定对象 或者 数组 等复杂的数据类型 我们看源码里面其实也是 去调用 reactive

使用 reactive 去修改值无须.value

reactive 的基本用法

1
2
3
4
5
import { reactive } from "vue";
let person = reactive({
name: "nagisa",
});
person.name = "caoysong";

数组异步赋值问题

这样赋值的页面是不会改变的因为会脱离响应式;

1
2
3
4
5
6
let person = reactive<number[]>([])
setTimeout(() => {
person = [1, 2, 3]
console.log(person);

},1000)

解决方案

方案一:

1
2
3
4
5
6
7
8
import { reactive } from 'vue'
let person = reactive<number[]>([])
setTimeout(() => {
const arr = [1, 2, 3]
person.push(...arr)
console.log(person);

},1000)

方案二:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// 包裹一层对象
type Person = {
list?: Array<number>,
};
let person =
reactive <
Person >
{
list: [],
};
setTimeout(() => {
const arr = [1, 2, 3];
person.list = arr;
console.log(person);
}, 1000);

readonly

拷贝一份 proxy 对象并将其设为已读;

1
2
3
4
5
import { reactive, readonly } from "vue";
const person = reactive({ count: 1 });
const copy = readonly(person);
//person.count++
copy.count++;

shallowReactive

只能对浅层的数据 如果是深层的数据只会改变值 不会改变视图

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<template>
<div>
<div>{{ state }}</div>
<button @click="change1">test1</button>
<button @click="change2">test2</button>
</div>
</template>
<script setup lang="ts">
import { shallowReactive } from 'vue'
const obj = {
a: 1,
first: {
b: 2,
second: {
c: 3
}
}
}
const state = shallowReactive(obj)
function change1() {
state.a = 7
}
function change2() {
state.first.b = 8
state.first.second.c = 9
console.log(state);
}
</script>
<style>
</style>