* shallowReactive:只處理了對象內最外層屬性的響應式(也就是淺響應式)
* shallowRef:只處理了 value 的響應式,不進行對象的 reactive 處理(也就是淺響應式)
* 什么時候用淺響應式呢?
* 一般情況下使用 ref 和 reactive 即可
* 如果有一個對象數據,結構比較深,但變化時只是外層屬性變化時,可以使用 shallowReactive
* 如果有一個對象數據,后面會產生新的對象來替換時,可以使用 shallowRef
```html
<template>
<!-- 3. 查看界面變化 -->
<h2>reactive: {{ reactive01 }}</h2>
<h2>shallowReactive: {{ shallowReactive01 }}</h2>
<h2>ref: {{ ref01 }}</h2>
<h2>shallowRef: {{ shallowRef01 }}</h2>
<hr />
<button @click="update">更新數據</button>
</template>
<script lang="ts">
import {
defineComponent,
reactive,
ref,
shallowReactive,
shallowRef,
} from "vue";
export default defineComponent({
setup() {
/* 1. 分別用4個不同的函數創建響應式對象 */
const reactive01 = reactive({
name: "張三",
age: 20,
car: {
name: "奔馳",
price: 100,
},
});
const shallowReactive01 = shallowReactive({
name: "張三",
age: 20,
car: {
name: "奔馳",
price: 100,
},
});
const ref01 = ref({
name: "張三",
age: 20,
car: {
name: "奔馳",
price: 100,
},
});
const shallowRef01 = shallowRef({
name: "張三",
age: 20,
car: {
name: "奔馳",
price: 100,
},
});
// 2. 更新第2層的數據
// shallowXX創建的對象第1層是可以被更新并實時渲染到界面,這里就不演示了,主要演示第2層的更新
const update = () => {
// reactive01.car.price += 100
// shallowReactive01.car.price += 100
// ref01.value.car.price += 100
// shallowRef01.value.car.price += 100
};
return {
reactive01,
shallowReactive01,
ref01,
shallowRef01,
update,
};
},
});
</script>
```
<br/>
更新數據時有以下2種組合,每種組合會產生不同的效果。
**1. shallowXX函數創建的對象單獨更新**
```js
// 更新第2層的數據
const update = () => {
shallowReactive01.car.price += 100;
shallowRef01.value.car.price += 100;
console.log(shallowReactive01.car.price, shallowRef01.value.car.price);
//200 200
//300 300
//400 400
//500 500
//... ...
};
```

數據確實已經被更新,但是不會顯示到界面上。
<br/>
**2. shallowXX與非shallow創建的對象放在一起更新**
```js
// 更新第2層的數據
const update = () => {
//下面三種組合更新效果都是一樣的
//(1)reactive與shallowXX放在一起更新
//(2)ref與shallowXX放在一起更新
//(3)reactive、ref、shallowXX放在一起更新
reactive01.car.price += 100
shallowReactive01.car.price += 100;
ref01.value.car.price += 100
shallowRef01.value.car.price += 100;
console.log(shallowReactive01.car.price, shallowRef01.value.car.price);
//200 200
//300 300
//400 400
//500 500
//... ...
}
```

將 shallowXX 函數創建的對象與非 shallow 函數創建的對象放在一起更新,shallowXX 創建的對象的深層會被更新并實時渲染到界面上。
- nodejs
- 同時安裝多個node版本
- Vue3
- 創建Vue3項目
- 使用 vue-cli 創建
- 使用 vite 創建
- 常用的Composition API
- setup
- ref
- reactive
- 響應數據原理
- setup細節
- reactive與ref細節
- 計算屬性與監視
- 生命周期函數
- toRefs
- 其它的Composition API
- shallowReactive與shallowRef
- readonly與shallowReadonly
- toRaw與markRaw
- toRef
- customRef
- provide與inject
- 響應式數據的判斷
- 組件
- Fragment片斷
- Teleport瞬移
- Suspense
- ES6
- Promise對象
- Promise作用
- 狀態與過程
- 基本使用
- 常用API
- async與await
- Axios