vue.jsvuejs3

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


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?


Solution

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