[Vuejs]-How to call this.function from inside another function within Vue

2๐Ÿ‘

โœ…

1) This is the problem of this binding. You can use the arrow function to solve this problem. CODESANDBOX

Pass arrow function instead of normal function in setTimeout

setTimeout(() => {
      this.logValues();
    }, 2000);

instead of

setTimeout(function(){
      this.logValues();
    }, 2000);

When you use a normal function then this binding is dependent on how the function is called. Here this will be Window object and there is no method named checkMounted on the window object and produces an error.

You can read more about this on stackoverflow


2) There is one more way that you could solve this problem, This is an old-school method and was used before ES6 arrow function. CODESANDBOX

  mounted() {
    const that = this;
    setTimeout(function () {
      that.logValues();
    }, 2000);
  },
๐Ÿ‘คDecPK

Leave a comment