【问题标题】:Vue JS - How to get function result in methods()Vue JS - 如何在方法()中获取函数结果
【发布时间】:2020-01-26 23:45:34
【问题描述】:

我正在尝试使用这种结构。

我将我的 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()
    }

}

我不明白为什么结果是未定义的,因为 getStationList() 函数被调用...当组件被挂载时,函数应该返回响应...我该如何解决这种情况?

【问题讨论】:

    标签: vue.js


    【解决方案1】:

    getStationList 是一个异步函数,所以你需要await 它的结果(或使用then)。例如:

    async mounted() {
      this.markers = await DashboardService.getStationList();
    },
    

    有关详细信息,另请参阅this question

    接下来,您在getStationList 的实现中缺少return

    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 [];
        }
      },
    };
    

    【讨论】:

      【解决方案2】:

      结果是undefined,因为getStationList 没有返回任何内容。

      您可以考虑将您的 api 调用转换为返回结果的 async 函数。

      const DashboardService = {
          async getStationList() {
              let url = '/api/stations/list';
              return ApiService.get(url);
          }
      }
      
      export default DashboardService
      

      在你的组件中

      methods: {
          async getMarkers() {
              let result = await DashboardService.getStationList();
              console.log(result);
      
         }
      },
      

      如果您不想使用async await 语法。您可以从您的服务中返回一个承诺并在您的组件上使用结果,如下所示:

      methods: {
          getMarkers() {
              DashboardService.getStationList().then(result => {
                  console.log(result);
              });
         }
      },
      

      【讨论】:

        猜你喜欢
        • 2019-08-03
        • 2017-06-05
        • 2020-10-02
        • 1970-01-01
        • 2012-02-05
        • 2019-08-30
        • 2018-11-16
        • 1970-01-01
        • 2020-07-03
        相关资源
        最近更新 更多