【问题标题】:Populating Vue data based on response from axios GET request根据来自 axios GET 请求的响应填充 Vue 数据
【发布时间】:2019-06-08 00:51:58
【问题描述】:

假设我向 API 端点发出 GET 请求,该端点将返回 10 张图像,如下所示:

export default {
    data: function() {
        return {
            images: []
        }
    },
    mounted() {
        axios.get('https://api.unsplash.com/photos/?client_id=secret')
        .then(response => {
            for (var i = 0; i < response.data.length; i++) {
                this.images.push(response.data[i]);
            }
        })
        .catch((error) => console.log(error));
    }
}

我是否必须初始化一个空图像数组,然后像我在代码中所做的那样使用 for 循环使用响应填充它,还是没有必要?除非我自己将它们实际存储在自己的变量中,否则我真的想不出任何其他方法来循环返回的图像。

【问题讨论】:

  • 什么意思?如果您可以以其他方式编写“普通 for 循环”?为什么你不能this.images = response.data;
  • 我是否必须像目前所做的那样自己创建图像数组数据并将所有对象推送到其中?

标签: javascript vue.js vuejs2 axios


【解决方案1】:

我看不出这有什么问题。不过,分配它会更干净,因为您只会在安装的钩子中获取一次图像。

export default {
    data: function() {
        return {
            images: []
        }
    },
    mounted() {
        axios.get('https://api.unsplash.com/photos/?client_id=secret')
        .then(response => {
            this.images = response.data;
        })
        .catch((error) => console.log(error));
    }
}

【讨论】:

  • 嗯,我不知道我能做到这一点。绝对干净。
  • 只要确保您在数据选项中正确定义了属性,以便 Vue 可以毫无问题地对其做出反应。如果您稍后要加载更多图像,您仍然需要循环/推送,或者您可以使用 array.concat() 并再次重新分配。
猜你喜欢
  • 1970-01-01
  • 2015-11-15
  • 1970-01-01
  • 2019-06-20
  • 1970-01-01
  • 2020-08-19
  • 2018-10-16
  • 2020-02-14
  • 2021-08-01
相关资源
最近更新 更多