1

I am trying to log whenever something changes value inside of the array, it only console logs items whenever I add or remove it, but how can I log whenever something has been changed in it? For e.g I'd like to see item.Circle.position to be console logged after it's changed.

And yes, I've tried watch with deep: true, but won't log it as well.

watchEffect(async () => {
    await map.value.circles.forEach((item, i) => console.log(item.Circle, i))
})
watch(async () => {
    await map.value.circles.forEach((item, i) => console.log(toRaw(item.Circle), i))
}, { deep: true })
Penny Liu
  • 15,447
  • 5
  • 79
  • 98
Dave
  • 1
  • 1
  • 9
  • 38
  • https://stackoverflow.com/questions/41135188/vue-deep-watching-an-array-of-objects-and-calculating-the-change maybe this can help – omerS Jun 24 '21 at 21:31
  • Your `watch()` call needs to pass `map` as the first arg, as seen in this [demo](https://stackblitz.com/edit/vue-deep-watcher?file=src/components/MapCircles.vue). You commented that it crashes when you try this. Can you fork the demo to reproduce that problem? – tony19 Jun 24 '21 at 23:59
  • Is item.Circle reactive? As it was said in previous answer, it's incorrect to use watch without inputs. This isn't a common case, a workable example that can be debugged is advisable. – Estus Flask Jun 25 '21 at 06:46

1 Answers1

1

Try to watch a copy of the array value, using the function syntax as the first parameter

watch(() => [...map.value], async () => {
    await map.value.circles.forEach((item, i) => console.log(toRaw(item.Circle), i))
})

If your array contains 'deep' objects, you need to make a deep copy. Here is an example using lodash

watch(() => _.cloneDeep(map.value), async () => {
    await map.value.circles.forEach((item, i) => console.log(toRaw(item.Circle), i))
})

One final issue may be the way you mutate your data. Try to use Vue.set(...) instead of directly adding properties such as map['foo'] = 'bar' or map.foo = 'bar' to ensure new properties are made reactive.

Steven Spungin
  • 27,002
  • 5
  • 88
  • 78