【问题标题】:Cannot assign axios response value to a variable - vue.js无法将 axios 响应值分配给变量 - vue.js
【发布时间】:2019-07-18 20:47:03
【问题描述】:

我创建了一个数组lists,其中包含一些字符串。 现在我想遍历lists(即getSubs())并发出一个Axios请求。此请求每次都应包含来自lists 的一个字符串。

我的代码:

computed: {
  subscribers: {
    get() {
      return this.$store.state.subscribers;
    },
    set(value) {
      this.$store.commit('updateSubscribers', value);
    },
  },
},
methods: {
  getLodzkie() {
    axios
      .get(`correct_domain/lodzkietargi/get`)
      .then((response) => {
        this.subscribers = [];
        this.subscribers.push.apply(this.subscribers, response.data)
      })
      .catch(function(error) {
        console.log(error);
      })
  },
  getSubs() {
    function getSub(value) {
      axios
      .get(`correct_domain/${value}/get`)
      .then((response) => {
        this.subscribers.push.apply(this.subscribers, response.data)
      })
      .catch(function(error) {
        console.log(error);
      });
      console.log(value);
    }
    this.lists.forEach(function(entry) {
      getSub.call(null, entry);
    });
  },

getLodzkie() 效果很好

【问题讨论】:

标签: vue.js vuejs2 axios vuex


【解决方案1】:

非常感谢@ourmandave。这对我很有帮助。

重写以下函数:

getSubs() {
  let listsReqs = this.lists.map(list => {
    return axios.get(`correct_domain/${list}/get`);
  });
  axios.all(listsReqs)
  .then(axios.spread((...responses) => {
    responses.forEach(res => this.subscribers.push.apply(this.subscribers, res.data));
  })
)},

【讨论】:

    猜你喜欢
    • 2020-10-23
    • 2020-12-25
    • 1970-01-01
    • 1970-01-01
    • 2019-12-28
    • 1970-01-01
    • 1970-01-01
    • 2016-04-20
    • 2020-07-02
    相关资源
    最近更新 更多