<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)
  1. 对于对象(Object、Array)的监听要加deep
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐