Article directory
1. Question 1: The responsive data defined by reactive has no oldValue
question
- Monitoring a responsive data defined by reactive cannot get oldValue correctly
- The source code is as follows:
<script setup lang="ts">
import {
ref, reactive, watch } from "vue";
const dataInfo = reactive(
{
'name': '法外狂徒张三',
'age': 15
}
)
watch(dataInfo, (newValue, oldValue) => {
console.log(newValue, oldValue);
})
setTimeout(() => {
dataInfo.age++;
dataInfo.name += '!'
}, 5200);
</script>
- The result of the operation is as follows
- It can be seen from the running results that the obtained newValue and oldValue are the same
analyze
We can learn from the Vue3 official websitenewValue
: here and oldValue
are equal, unless state.someObject is completely replaced
solve
If you want to use the value of oldValue during development, you can use the value in the object as a ref to wrap it separately
2. Question 2: Watch has enabled in-depth monitoring by default and cannot be turned off
Article directory
question
- When we want to monitor a multi-level data, Vue2 needs to enable in-depth monitoring, but Vue3 will enable it by default. When we choose to turn off in-depth monitoring, it cannot be turned off
- The source code is as follows:
<script setup lang="ts">
import {
ref, reactive, watch } from "vue";
const dataInfo = reactive(
{
'name': '法外狂徒张三',
'age': 15,
'data':{
data1:1,
data2:2,
}
)
watch(dataInfo, (newValue, oldValue) => {
console.log(newValue, oldValue);
},{
deep:false})
setTimeout(() => {
dataInfo.data.data1++;
dataInfo.name += '!'
}, 5200);
</script>
analyze
When we want to monitor a multi-level data, Vue2 needs to enable in-depth monitoring, but Vue3 will enable it by default. When we choose to turn off in-depth monitoring, it cannot be turned off
solve
Monitoring reactive defines the inward level of reactive objects, and it is useful to enable deep monitoring deep:true
<script setup lang="ts">
import {
ref, reactive, watch } from "vue";
const dataInfo = reactive(
{
'name': '法外狂徒张三',
'age': 15,
'data':{
data1:1,
data2:2,
}
)
watch(dataInfo.data, (newValue, oldValue) => {
console.log(newValue, oldValue);
},{
deep:true})
setTimeout(() => {
dataInfo.data.data1++;
dataInfo.name += '!'
}, 5200);
</script>