Luca Reghellin
Luca Reghellin

Reputation: 8101

How to force Vuejs to run watch functions

I'm using Vue and have several watch functions like:

  ,watch:{
    'form.screw.thread':function(val, oldval){
      var box = this.$refs.screw_thread_radios;
      this.form.screw.thread_t = box.querySelector('input[value="' + val + '"] + label .name').innerHTML;
      this.form.screw.thread_image = UrlUtilities.get_file_in_url(box.querySelector('input[value="' + val + '"] + label img').getAttribute('src'));
    }

   [etc..]

My problem is that all those props will evaluate only on change (after changing) or, in other words, after interacting with the view/ui. Instead, I need al of them to evaluate one time also on init. Is there a wa? Can't find useful infos on docs.

Upvotes: 2

Views: 3919

Answers (2)

Stephan-v
Stephan-v

Reputation: 20289

You can pass in the immediate property:

https://v2.vuejs.org/v2/api/#vm-options

Example:

watch: {
  foo: {
    immediate: true,
    handler(nv, ov) { ... }
  }
}

Also another option would be to abstract the logic into a method and run it on a lifecycle hook. This would be useful if you also need to run the logic somewhere else.

Upvotes: 3

Luca Reghellin
Luca Reghellin

Reputation: 8101

After some research, the answer is: you cannot do it reliably. Or, to be more precise, even by passing immediate: true, in your function scope you won't have access to the same properties you could from a lifecycle hook like 'mounted' (see comments above, for example $refs).

So I personally ended up abstracting the logic I needed into another function, defining it into the Vue's methods property. I then call that function both in mounted (for my init needs) and in watchers (instead of the original code) as needed.

Upvotes: 2

Related Questions