karlos
karlos

Reputation: 990

How to bind Vue js watchers to an array of objects

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.

Upvotes: 0

Views: 210

Answers (2)

Neha
Neha

Reputation: 2281

You can use a deep watcher for that

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

Upvotes: 1

Michael
Michael

Reputation: 5048

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.

Upvotes: 1

Related Questions