首页 > 解决方案 > 根据来自 axios GET 请求的响应填充 Vue 数据

问题描述

想象一下,我向 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 循环使用响应填充它,还是没有必要?我真的想不出任何其他方式来遍历返回的图像,除非我自己将它们存储在我自己的变量中。

标签: javascriptvue.jsvuejs2axios

解决方案


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

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));
    }
}

推荐阅读