文章目录
shallowReactive 与shallowRef
shallowReactive
- shallowReactive:只处理对象
最外层属性的响应式
(浅响应式)。
eg:
<template>
<h2>姓名:{{name }}</h2>
<h2>年龄:{{age }}</h2>
<h2>薪资:{{job.j1.salary }}</h2>
<button @click="name += '~'">修改姓名</button>
<button @click="age += 1">增长年龄</button>
<button @click="job.j1.salary++">涨薪</button>
</template>
<script>
import {shallowReactive, toRefs } from 'vue'
export default {
name: 'DemoVue',
setup() {
// 数据
let person = shallowReactive({
name: 'yang',
age: 18,
job: {
j1: {
salary: 20
}
}
})
return {
...toRefs(person)
}
}
}
</script>
效果:
shallowRef
- shallowRef:只处理
基本数据类型
的响应式,不进行对象的响应式处理。
使用场景
什么时候使用?
- 如果有一个对象数据,结构比较深,但变化时只是外层属性变化===> shallowReactive。
- 如果有一个对象数据,后续功能不会修改该对象中的属性,而是生新的对象来替换===> shallowRef。
readonly 与shallowReadonly
- readonly:让一个
响应式数据
变为只读的
(深只读)。 - shallowReadonly:让一个响应式数据变为只读的(浅只读)。
应用场景:不希望数据被修改时。 - 格式:
person = readonly(person)
readonly例子
<template>
<h2>姓名:{{name }}</h2>
<h2>年龄:{{age }}</h2>
<h2>薪资:{{job.j1.salary }}</h2>
<button @click="name += '~'">修改姓名</button>
<button @click="age += 1">增长年龄</button>
<button @click="job.j1.salary++">涨薪</button>
<hr />
<h2>sum:{{sum}}</h2>
<button @click="sum++">sum++</button>
</template>
<script>
import {reactive, toRefs ,ref,readonly,shallowReadonly} from 'vue'
export default {
name: 'DemoVue',
setup() {
// 数据
let sum = ref(0)
// let person = shallowReactive({
let person = reactive({
name: 'yang',
age: 18,
job: {
j1: {
salary: 20
}
}
})
person = readonly(person)
sum = readonly(sum)
return {
sum,
...toRefs(person)
}
}
}
</script>
效果:
shallowReadonly例子
<template>
<h2>姓名:{{name }}</h2>
<h2>年龄:{{age }}</h2>
<h2>薪资:{{job.j1.salary }}</h2>
<button @click="name += '~'">修改姓名</button>
<button @click="age += 1">增长年龄</button>
<button @click="job.j1.salary++">涨薪</button>
<hr />
<h2>sum:{{sum}}</h2>
<button @click="sum++">sum++</button>
</template>
<script>
import {reactive, toRefs ,ref,readonly,shallowReadonly} from 'vue'
export default {
name: 'DemoVue',
setup() {
// 数据
let sum = ref(0)
// let person = shallowReactive({
let person = reactive({
name: 'yang',
age: 18,
job: {
j1: {
salary: 20
}
}
})
person = shallowReadonly(person)
return {
sum,
...toRefs(person)
}
}
}
</script>
效果: