javascript - 根据来自 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 循环使用响应填充它,还是没有必要?我真的想不出任何其他方式来遍历返回的图像,除非我自己将它们存储在我自己的变量中。
解决方案
我看不出这有什么问题。不过,分配它要干净得多,因为您只能在安装的钩子中获取一次图像。
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));
}
}
推荐阅读
- android - 无法在 Android Studio 中安装 Android NDK (ndk-bundle):无法 mkdirs
- html - 服务器端口上的 HTML 表单发布,而不是 URL
- python - 导入 python 代码,然后从企业架构师 uml 图中生成不同的(例如 java)代码
- android - 允许在 NestedScrollView 中使用 RecyclerView 回收项目
- ios - 在更改 MKMapView 的高度时,将延迟固定到 MKMapView 的中心
- javascript - 测试工作的 Angular 组件 - TypeError: $(...).somename is not a function
- laravel - 如果数据无效,laravel 重定向其他页面
- python - 我应该在每个虚拟环境中安装 conda 吗?
- react-testing-library - 使用 React 测试库获取 HTML 元素?
- css - 在 div 中以不同方式对齐 h1 到 h6