简体   繁体   English

在Vue中的方法内部调用方法

[英]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() ?我如何调用success() My error this.after is not a function我的错误this.after不是 function

You need to use an arrow function to preserve the this context:您需要使用箭头 function来保留this上下文:

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

Otherwise the callback function injects its own this否则回调 function 会注入自己的this

Although using arrow function is the best way to achieve this, you can store this inside a const before calling setTimeout method:尽管使用箭头 function 是实现此目的的最佳方法,但您可以在调用setTimeout方法之前将this存储在const中:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM