观察数组中的当前值变化 [英] Watch for current value changes in array

查看:25
本文介绍了观察数组中的当前值变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每当它改变半径和中心时,我想观察每个项目,无论何时我想控制台.记录项目索引和值

I want to watch for each item whenever It changes the radius and center, whenever It does I want to console.log the item index and the values

let map = ref(null)map.value.circles 是一个数组当我使用这个 watch 功能时,它只在加载时显示一次值,我想在每次它在我的控制台中更改时看到它.我该怎么做?

let map = ref(null) map.value.circles is an array When I use this watch function, it only displays the value once on load, I want to see it everytime it changes in my console. How can I do this?

     watch(() => map.value, (currentValue) => {
        currentValue.circles.forEach((item) => {
          console.log(item)
        })
      },
    );

所以当 item.circle.center.lat() 和 lng 发生变化时,我想控制台记录它,而不是每个项目.

So when item.circle.center.lat() and lng changes, I want to console log it, not every item.

每当我现在更新任何项目时,都不会记录任何内容.

Whenever I update any item now, nothing logs.

推荐答案

默认情况下,Vue 对象(包括数组)仅在创建或替换时触发 watch.为了观察数组/对象的变化,您需要包含 deep 选项 (deep: true).

By default in Vue objects (which include arrays) only trigger the watch when created or replaced. In order to watch for mutations of arrays/objects you need to include the deep option (deep: true).

您需要稍微修改您的手表,以便您可以传入深度选项 - 我相信它最终会是这样的:

You'll need to slightly modify your watch so you can pass in the deep option - I believe it will end up looking like this:

watch(() => map.value, 
  (currentValue) => {
    currentValue.circles.forEach((item) => {
      console.log(item)
    })
  },
  {deep: true}
);

来源:

Vue 3 文档关于使用 deep

关于使用 watch 的 Vue 3 文档

Vue 3 使用 Deep 和 watch() &组合 API

这篇关于观察数组中的当前值变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆