【问题标题】:How to return value in VueJS Mixin如何在 VueJS Mixin 中返回值
【发布时间】:2017-01-18 12:44:55
【问题描述】:

我目前正在用 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 部分中不起作用...

【问题讨论】:

    标签: javascript vue.js vue-resource vue-component


    【解决方案1】:

    您的callAPI 没有return 语句,因此它返回undefined。如果它返回您的$http 调用,它仍然不会给您response,而是a Promise,所以您会想要做类似的事情

    let api_response;
    this.callAPI('POST', '/auth', credentials).then((response) => api_response = response);
    

    【讨论】:

    • 谢谢。另一种选择是做return this.$http({...
    • 如果你 return this.$http({... 你会得到一个 Promise,而不是一个值。
    猜你喜欢
    • 2020-10-17
    • 2019-02-16
    • 2017-11-15
    • 2020-05-10
    • 2014-10-29
    • 1970-01-01
    • 2020-05-30
    • 2020-11-23
    • 2021-07-22
    相关资源
    最近更新 更多