Jar*_*vis 1 javascript vue.js vuejs2
在 Vue 组件中:
import { someRequestMethod } from '@/api/requ'
...
methods: {
testMethod() {
someRequestMethod(someRequestData).then(function() {
this.outMethod_01()
}).then(function() {
this.outMethod_02()
})
}
outMethod_01() {
console.log('I am an outer method 01.');
}
outMethod_02() {
console.log('I am an outer method 02.');
}
}
Run Code Online (Sandbox Code Playgroud)
当我打电话时testMethod,有Promise回应。然后我想调用outMethod_01如果成功,outMethod_02如果有错误。但我有错误outMethod_01 is undefined和outMethod_02 is undefined。
那么如何调用外部方法Promise呢?
您应该使用箭头函数语法(params) => {...code}而不是function(params) {...code}. 箭头函数this是从作用域继承而来的。在常规函数中,this是函数本身(它有自己的作用域)。
您可以在此处了解更多信息:https : //hackernoon.com/javascript-es6-arrow-functions-and-lexical-this-f2a3e2a5e8c4
如果您不能使用 ES6 语法,您可以执行以下操作:
methods: {
testMethod() {
var self = this;
someRequestMethod(someRequestData).then(function() {
self.outMethod_01()
}).then(function() {
self.outMethod_02()
})
}
outMethod_01() {
console.log('I am an outer method 01.');
}
outMethod_02() {
console.log('I am an outer method 02.');
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5465 次 |
| 最近记录: |