Home > Software design >  (VueJS v3) How would I watch for array mutations (inserted, removed, replaced) of an reactive array?
(VueJS v3) How would I watch for array mutations (inserted, removed, replaced) of an reactive array?

Time:03-04

say I have a reactive array, how would I watch it so that I know what is inserted, removed and replaced when push(), splice() is called? Thanks!

CodePudding user response:

On Vue3 you can do this on your script

<script setup>
watchEffect(() => { console.log(nameOfYourArray)})
</script>

Or on Vue 2 and Vue3 with Option API

     Watch: {
      nameofYourArray: {
        deep: true,
        immediate:true,
        handler(newVal,oldVal){
        console.log(newVal)
        }
      }
   }

if you use 2eme solutions you don't forget to add deep otherwise it won't work on child array

CodePudding user response:

Since splice etc doesn't directly assign a new value to the array, Vue's reactivity system won't pick up on the changes and the watcher won't fire.

You can, however, create a computed that copies the array and then watch that:

computed: {
  myArray() {
    return this.my_array.slice();
  },
},
data() {
  return {
    my_array: [],
  };
},
watch: {
  myArray(newArray, oldArray) {
    // do stuff
  },
},

Demo

  • Related