<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
}
)
1.对arr.value进行深拷贝
JSON.parse(JSON.stringify(arr.value)
- 对于对象(Object、Array)的监听要加deep