观察数组中的当前值变化

编程入门 行业动态 更新时间:2024-10-16 21:30:17
本文介绍了观察数组中的当前值变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

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

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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-27 00:16:15,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1144916.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组中

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!