我正在尝试使用这种结构。
我在服务文件中调用 axios,然后在 vue 文件中调用它们。
所以我有这个js文件
const DashboardService = {
getStationList() {
let url = '/api/stations/list'
ApiService.get(url) //ApiService is an Axios wrapper
.then(response => {
console.log(response.data) //data are logged, function is called
response.data
})
}
}
export default DashboardService
然后在 Vue 文件中我有这个:
import DashboardService from '@/_services/admindashboard.service'
export default {
methods: {
getMarkers() {
let result = DashboardService.getStationList()
console.log(result) //undefined
}},
mounted() {
this.getMarkers()
}
}
我不明白为什么结果未定义,因为 che getStationList() 函数被调用......当组件被安装时,函数应该已经返回响应......我该如何解决这种情况?
getStationList
是一个异步函数,所以你需要await
它的结果(或使用then
)。例如:
async mounted() {
this.markers = await DashboardService.getStationList();
},
另请参阅此问题以获取更多详细信息。
接下来,您return
在getStationList
.
const DashboardService = {
getStationList() {
const url = '/api/stations/list';
ApiService.get(url).then(response => {
return response.data;
});
},
};
也许:
const DashboardService = {
async getStationList() {
const url = '/api/stations/list';
try {
const response = await ApiService.get(url);
return response.data;
} catch (error) {
console.error(error);
return [];
}
},
};
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句