
解决vue3中,watch监听数组、reactive json对象,新值和旧值是一样的
json
适用于现代 C++ 的 JSON。
项目地址:https://gitcode.com/gh_mirrors/js/json
·
文章转载 解决vue3中,watch监听数组时,新值和旧值是一样的
一、数组对象watch 新旧的值一样
<template>
<div @click="onClick">点击</div>
</template>
<script setup>
import { ref,watch } from "vue"
const arr = ref([1, 2])
function onClick() {
arr.value.push(1)
}
watch(
arr,
(n, o) => {
console.log("arr", n, o)
},
{
deep:true
}
)
<script >
结果如下:

原因说明:

解决办法
watch(
()=>JSON.parse(JSON.stringify(arr.value)),
(n, o) => {
debugger
console.log("arr", n, o)
},
{
deep:true
}
)
说明:
- 对arr.value进行深拷贝
JSON.parse(JSON.stringify(arr.value)
- 对于对象(Object、Array)的监听要加deep
二、JSON reactive对象watch 新旧的值一样
- 无法区分新旧值的逻辑
const vectorLayerMap = reactive({}) // 定义图层对象
watch(vectorLayerMap
}, (newValue, oldValue) => {
console.log('newValue, oldValue 数据发生了变化', newValue, oldValue)
}, {
deep: true
})
- 解决办法: 区分新旧值的逻辑
const vectorLayerMap = reactive({}) // 定义图层对象
watch(() => {
return {
...vectorLayerMap
}
}, (newValue, oldValue) => {
console.log('newValue, oldValue 数据发生了变化', newValue, oldValue)
}, {
deep: true
})
三、监听reactive 对象 字段的变化
export const showLayerConfig = reactive({
// camera: false, // 普通点位
camera: true, // 普通点位
signal: false, // 信号机
enforce: false, // 执法记录仪
interphone: false // 对讲机
})
watch(() => ({
...showLayerConfig
}), (newVal, oldValue) => {
console.log(newVal, oldValue)
// 1. 找出 改变的是哪个图层
const keys = Object.keys(newVal)
let changeKey = ''
for (let i = 0; i < keys.length; i++) {
const key = keys[i]
if (newVal[key] !== oldValue[key]) {
changeKey = key
break
}
}
console.log("变化字段是:", changeKey)
}, {
deep: true
})

适用于现代 C++ 的 JSON。
最近提交(Master分支:2 个月前 )
960b763e
4 个月前
8c391e04
7 个月前
更多推荐

所有评论(0)