我目前正在用 Vuejs 开发一个 webapp。我创建了一个可以全局访问的 Mixin,它处理对我的 api 的任何请求:
export default {
data() {
return {
apiURL: 'http://example.com/api',
timeout: 10000,
};
},
methods: {
callAPI(method, url, body) {
this.$http({
url: this.apiURL + url,
method,
body,
timeout: this.timeout,
})
.then((response) =>
response,
(response) => {
if (response.data.error) {
this.error = response.data.error;
} else {
this.error = 'We can\'t connect to the server. Please try again in a few minutes.';
}
return response;
});
// return 'test';
},
},
};
现在,在我的一些组件中,我调用了 api 函数:
const api_response = this.callAPI('POST', '/auth', credentials);
alert (api_response);
它工作正常,但有一件事没有按预期工作。我希望我的api_response
常数具有的价值,response
但它总是undefined
。所以每次我收到这个警报时undefined
。这怎么可能?当我取消注释return 'test'
它的行时:我收到了一个警报test
,但它似乎在该this.$http
部分中不起作用......