5

Suppose I have a watcher that is watching an array mylist

watch {
 mylist:function(){
    //Code
 }
}

How can I programatically trigger an update on the variable and run the code (if the variable is unchanged)? How can I trigger an update if the watched variable is a nested object/array or a simple string?

1
  • 1
    Please provide some details about why you want to do it this way, maybe there is a better way to do it. Commented Apr 18, 2017 at 9:20

3 Answers 3

7

Since you didn't provide any description regarding the actual use-case, the best you can probably do is to extract a method that is called in call this method manually.

data: function() {
   return { myList: [] }
},

watch: {
   myList: this.handleListChange
},

methods: {
   handleListChange: function(a, b) {
       // .. do whatever you want to do in the watch method
   }
}

To trigger the "watch" method you can now simply call your handleListChange method manually.

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

Comments

2

There are 2 questions:

How can I programatically trigger an update on the variable and run the code if the variable is unchanged?

You can hack it this way:

this._watchers.find(w => w.expression === "mylist").cb(this.mylist);

However, it's not part of the official Vue API. The _watchers list is rather an implementation detail. It may change in the future without any notice.


How can I trigger an update if the watched variable is a nested object/array?

Use a deep watcher:

watch: {
  mylist: {
    handler: function(val) {
      // Code
    },
    deep: true
  }
}

Working example: https://jsfiddle.net/LukaszWiktor/zjagahq2/

Comments

1

Here is how i did it
Frank was on to something, i just couldn't access the "this" context like suggested
so all had to do was pass all the args to the method.

watch: {
   myList: (...args) { this.handleListChange(...args) },
}

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.