在 Vue 中遍历 API 响应有两种主要方式:对于数组响应,使用 v-for 指令和 response.data 变量。对于对象响应,使用 v-for="const" 指令和 Object.entries(response.data) 将对象转换为键值对数组。

如何在 Vue 中遍历 API 响应
在 Vue.js 中,有两种主要方式可以遍历 API 响应:
方法 1:使用 v-for 指令
<code class="html"><ul> <li v-for="item in response.data">...</li> </ul></code>
此方法适用于数组响应。response.data 应该是包含数据的数组。
立即学习“前端免费学习笔记(深入)”;
方法 2:使用 v-for="const" 指令
<code class="html"><ul> <li v-for="const [key, value] of Object.entries(response.data)">...</li> </ul></code>
此方法适用于对象响应。response.data 应该是包含数据的对象。Object.entries() 方法将对象转换为键值对的数组。
示例:使用 v-for 指令遍历数组响应
<code class="javascript">const { ref, onMounted } = Vue;
const response = ref([]);
onMounted(async () => {
const res = await fetch('https://example.com/api/data');
response.value = await res.json();
});
const app = Vue.createApp({
setup() {
return { response };
},
template: `<ul><li v-for="item in response">{{ item }}</li></ul>`
});
app.mount('#app');</code>示例:使用 v-for="const" 指令遍历对象响应
<code class="javascript">const { ref, onMounted } = Vue;
const response = ref({});
onMounted(async () => {
const res = await fetch('https://example.com/api/data');
response.value = await res.json();
});
const app = Vue.createApp({
setup() {
return { response };
},
template: `<ul><li v-for="const [key, value] of Object.entries(response)">{{ key }}: {{ value }}</li></ul>`
});
app.mount('#app');</code>以上就是vue怎么遍历接口的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号