【发布时间】:2021-07-19 14:48:21
【问题描述】:
我正在学习 vue.js 并坚持承诺的概念。我希望使用来自 API 调用的数据来初始化我的变量之一,并且我想确保 axios 调用将是通用的:
{
data: {
list: [],
},
methods: {
ShowList: function () {
return this.Axios_GET('/api/Api_Store').then(items => {
this.list = items;
});
},
Axios_GET: function (apiurl) {
// I want to keep this as a reusable method and don't want to bind variable inside this method
this.StartProgress();
axios({ method: 'get', url: apiurl }).then((response) => {
this.StopProgress();
return Response.data;
}).catch((error) => {
this.StopProgress();
}).then(function () {
});
},
}
};
当我尝试ShowList 时,出现以下错误:
Error in mounted hook: "TypeError: Cannot read property 'then' of undefined"
我想设置 ShowList 函数以从 API 获取数据,如下所示(概念上)
this.list = this.Axios_GET('/api/Api_Store')
注意:StartProgress 和 StopProgress 函数已经定义并且工作正常。
【问题讨论】:
-
你只是忘了
return函数中的任何东西,所以它返回undefined -
你能不能只提一下哪个函数或者发布正确的sn-p
-
在这个
Axios_GET: function (apiurl) {你必须像return axios({ method: 'get', url: apiurl }).then((response) => {一样返回。 -
@Ravikumar 但还是 this.list = items;未定义,但在 Axios_GET 中调试 axios 响应时我可以看到数据
-
@SreenathGanga,你不需要第二个然后在
Axios_GET,只需删除它就可以了。
标签: javascript vue.js promise axios