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

如何在 Vue 中遍历 API 响应
在 Vue.js 中,有两种主要方式可以遍历 API 响应:
方法 1:使用 v-for 指令
登录后复制登录后复制
- …
此方法适用于数组响应。response.data 应该是包含数据的数组。
方法 2:使用 v-for=”const” 指令
登录后复制登录后复制
- …
此方法适用于对象响应。response.data 应该是包含数据的对象。Object.entries() 方法将对象转换为键值对的数组。
示例:使用 v-for 指令遍历数组响应
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: `
登录后复制
- {{ item }}
`
});
app.mount(‘#app’);
示例:使用 v-for=”const” 指令遍历对象响应
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: `
登录后复制
- {{ key }}: {{ value }}
`
});
app.mount(‘#app’);
以上就是vue怎么遍历接口的详细内容,更多请关注叮当号网其它相关文章!
文章来自互联网,只做分享使用。发布者:木子,转转请注明出处:https://www.dingdanghao.com/article/497668.html
