【问题标题】:How to call service from component which are in different files?如何从不同文件中的组件调用服务?
【发布时间】:2018-05-12 23:53:09
【问题描述】:
filename: service.js
let getCorporateRequests = function() {
   let url = "http://corptest.mocklab.io/thing/2";
   Vue.axios.get(url).then((response) => {
     return response;
   })
}

在组件中

service.getCorporateRequests().then(function(data){
 console.log(data);
})

它给出“无法读取未定义的属性'then'”。

【问题讨论】:

  • 您是在service.js 中导出函数还是在组件中导入它?
  • 是的。那是我的错。谢谢你。返回一个承诺将解决问题。

标签: vue.js vuejs2 vue-component axios


【解决方案1】:

导出getCorporateRequests()并在组件中导入后

您的 getCorporateRequests 函数未返回承诺,因此您无法使用 getCorporateRequests().then()

所以让你的getCorporateRequests()返回一个承诺

filename: service.js
let getCorporateRequests = function() {
   let url = "http://corptest.mocklab.io/thing/2";
   return Vue.axios.get(url);
} 

现在您可以在您的组件中链接then(),如下所示:

service.getCorporateRequests().then(function(data){
    console.log(data);
})`

【讨论】:

    猜你喜欢
    • 2014-06-27
    • 1970-01-01
    • 2019-04-17
    • 1970-01-01
    • 2016-10-14
    • 1970-01-01
    • 2021-04-09
    • 2021-10-29
    相关资源
    最近更新 更多