0

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.

2
  • 1
    Hey, I don't really get the need. You want to bind watchers to all your array objects ? Commented Jun 3, 2019 at 9:52
  • Yes. I will change the title of the question. Commented Jun 3, 2019 at 9:54

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

You can use a deep watcher for that

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.