Harry Wardana
Harry Wardana

Reputation: 277

Call a method inside a method in Vue

I have methods:

methods: {
  submit () {
    this.loading = true
    setTimeout(function () {
      this.loading = false
      this.success() // how to call success() ?
    }, 3000)
  },
  success() {
    this.$store.dispatch('Auth/register', this.register)
  }
}

How do I call success()? My error this.after is not a function

Upvotes: 1

Views: 1391

Answers (2)

Konstantin Srdjanov
Konstantin Srdjanov

Reputation: 1

Although using arrow function is the best way to achieve this, you can store this inside a const before calling setTimeout method:

methods: {
  submit () {
    const _self = this
    _self.loading = true
    setTimeout(function () {
      _self.loading = false
      _self.success()
    }, 3000)
  },
  success() {
    this.$store.dispatch('Auth/register', this.register)
  }
}

Upvotes: 0

Dan
Dan

Reputation: 63139

You need to use an arrow function to preserve the this context:

setTimeout(() => {
  this.loading = false
  this.success();  // this is fine
}, 3000)

Otherwise the callback function injects its own this

Upvotes: 4

Related Questions