Home » vue » How to bind Vue js watchers to an array of objects

How to bind Vue js watchers to an array of objects

Posted by: admin November 26, 2021 Leave a comment

Questions:

I have an array that contains many objects like this :

[{x: updateX}, {y: updateY} ]

By using this array, I want to generate Vue js watchers automatically like this:

      watch: {
     x(){
         this.updateX()
       },
     y(){
         this.updateY()
       }
 } 

I only know that vue keep watchers as array.

Answers:

you can create an array and return from it a list of functions something like this:

data(){ return {
  watcherArray: [];
}
}
methods: {
   pushToWatchersArray() {
      this.watcherArray.push(someValue);
    }
    returnNewWatchers(){
       return { this.watchersArray.map(watcher => return `${watcher}(){ 
       this.updatewatcher()}
    }
watch: {
    [...this.returnNewWatchers()]
 } 

You may also need to rerender the component when changing the watchers, I am not sure about this, in addition you may need a separate watcher to watch for changes on the array to do this rerender.

###

You can use a deep watcher for that

watch: {
  arr: {
     handler(val){
       // do stuff
     },
     deep: true
  }
}