Home > Mobile >  how do I attach a watcher to each element in an array
how do I attach a watcher to each element in an array

Time:08-19

I have a bunch of js objects in an array. I want to add a watch to every item in the array. So that I can send out a change, and the desired item will turn on, while others will turn off.

Or is that too expensive?

CodePudding user response:

You can use the deep property for that problem like so

new Vue({
  ...
  watch: {
    things: {
      handler: function (val, oldVal) {
        console.log('a thing changed')
      },
      deep: true
    }
  },
  ...
})

You can read more about that topic here

CodePudding user response:

Since you're using Vue 3 it's common to use composition API which has a different syntax than options one :

import {watch, ref} from 'vue'
...
const items=ref([])

watch(items,(newVal,oldVal)=>{
    //do something
},{
  deep:true
})

if the array is not a ref, the first parameter is a callback function that returns the property :

import {watch} from 'vue'
...
...

watch(()=>props.items,(newVal,oldVal)=>{
    //do something
},{
  deep:true
})
  • Related