Is it possible to use `this.methodName` in component `watch: ` object?


#1
  watch: {
    'params.page': 'update' // TODO: Cannot use `this.update` here, why?
  },
  methods: {
    update: function(){
      store.fetchItemsByPage(this.params.page, function(items){
        this.items = items;
      }.bind(this));
    }
  }

#2

Sure it is. What exactly is your problem? You already bind the callback function tot hay api call correctly, as well.


#3
watch: {
  'params.page': 'update'
}

works as expected, if I change 'update' to this.update like below:

watch: {
  'params.page': this.update
}

It doesn’t work. Why?


#4

And the code snippet comes from here:


#5

ah, I totally missunderstood the topic title, and missed the comment in the code example.

The reason has nothing to do with Vue specifically.

watch: {
  'params.page': this.update
}

In the above code, this.update will be evaluated when the module file is loaded, which is long before the component is actually created from these options.

At this point, this is not the component instance (because this component instance does not exist yet), it’s rather pointing to the module scope, which is undefined.


#6

Well, thank you.

if this.update in watch: { } object doesn’t work, then how could this.update in methods: { } object work?

like below:

methods: {
  funcName: function(){
    this.update(); // This will work
  }
}

#7

Well in this case, ít is within a function. So it will only be evaluated when that funcion is called - which happens after the component instance exists.


#8

@LinusBorg Now I understand. Thank you very much.