Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Watch for current value changes in array

Tags:

vue.js

vuejs3

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 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)
        })
      },
    );

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.

like image 458
Dave Avatar asked Jul 14 '26 01:07

Dave


1 Answers

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}
);

Sources:

Vue 3 docs about using deep

Vue 3 docs about using watch

Vue 3 Using Deep with watch() & Composition API

like image 97
vanblart Avatar answered Jul 17 '26 19:07

vanblart