shallowReactive与shallowRef
- shallowReactive:只处理了对象内最外层属性的响应式(也就是浅响应式)
- shallowRef:只处理了value的响应式。不进行对象的reactive处理。
- 什么时候用浅响应式呢?
- 一般情况下使用ref和reactive即可
- 如果有一个对象数据,结构比较深,但变化时只是外层属性变化,我们可以用
shallowReactive
- 如果有一个对象数据,后面会产生新的对象来替换,我们可以用
shallowRef
好家伙,不仅有浅拷贝,还有浅响应式!
<!--
* @Author: 41
* @Date: 2021-12-07 17:12:43
* @LastEditors: 41
* @LastEditTime: 2021-12-18 16:56:08
* @Description:
-->
<template>
<h2>shallowReactive和shallowRef</h2>
<h3>m1:{{m1}}</h3>
<h3>m2:{{m2}}</h3>
<h3>m3:{{m3}}</h3>
<h3>m4:{{m4}}</h3>
<hr>
<button @click=update> 更改数据</button>
</template>
<script lang="ts">
import {defineComponent, shallowReactive,reactive, shallowRef, ref} from 'vue'
export default defineComponent({
name:'App',
setup(){
const m1=reactive({
name:'41',
age:24,
car:{
name:'123',
color:'red'
}
})
const m2=shallowReactive({
name:'41',
age:24,
car:{
name:'123',
color:'red'
}
})
const m3=ref({
name:'41',
age:24,
car:{
name:'123',
color:'red'
}
})
const m4=shallowRef({
name:'41',
age:24,
car:{
name:'123',
color:'red'
}
})
const update=()=>{
// reactive深度响应式
// m1.name+='+'
// m1.car.name+='?'
// shallowReactive浅度响应式
// m2.name+='+'
// m2.car.name+='?' //单独没有效果
// Ref
// m3.value.car.name+='?'
// shallowRef
m4.value.name+='+'
m4.value.car.name+='?'
}
return{
m1,
m2,
m3,
m4,
update
}
}
})
</script>
- 总的来说
shallowReactive
就是没办法改深层的数据了,深层不是响应式
了 shallowRef
不会再将object自动转换成reactive了,如果shallowRef({}),数据就不再是响应式
了
readonly与shallowReadonly
- readonly
- 深度只读数据
- 获取一个对象(响应式或纯对象)或ref并返回原始代理的只读代理
- 只读代理是深层的:访问任何嵌套property也是只读的
- shallowReadonly
- 浅只读数据
- 创建一个代理,使其自身的property为只读,但不执行嵌套对象的深度只读转换
- 应用场景:
- 在某些特定情况下,我们可能不希望对数据进行更新的操作,那就可以包装生成一个只读代理对象来读取数据,而不能修改或删除
<template>
<h2>readonly与shallowReadonly</h2>
<h3>state:{{state2}}</h3>
<hr>
<button @click=update>更新数据</button>
</template>
<script lang="ts">
import {defineComponent,reactive, shallowReadonly} from 'vue'
export default defineComponent({
name:'App',
setup(){
const state=reactive({
name:'41',
age:24,
car:{
name:'123',
color:'yellow'
}
})
// const state2=readonly(state)
const state2=shallowReadonly(state)
const update=()=>{
console.log('ceshi');
// state2.name+='+' readonly无法改变
state2.car.name+='?' // shallowReadonly可以改变
}
return {
state,
state2,
update
}
}
})
</script>
这个shallow
就是浅层次的,深层可以改