【问题标题】:Call a method inside a method in Vue在Vue中的方法内部调用方法
【发布时间】:2021-03-29 23:24:21
【问题描述】:
我有方法:
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)
}
}
如何拨打success()?我的错误this.after 不是函数
【问题讨论】:
标签:
javascript
vue.js
vuejs2
vue-component
vuex
【解决方案1】:
您需要使用arrow function 来保留this 上下文:
setTimeout(() => {
this.loading = false
this.success(); // this is fine
}, 3000)
否则回调函数会注入自己的this
【解决方案2】:
虽然使用箭头函数是实现此目的的最佳方法,但您可以在调用 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)
}
}