我如何迭代 Vue.js 中的 API 响应?
How do i iterate over API response in Vue.js?
您好,我是 Vue 新手,如何在我的模板中遍历它并呈现它?
我可以控制台记录所有内容,但无法在我的页面上呈现它。
API URL : https://private-922d75-recruitmenttechnicaltest.apiary-mock.com/customexercises/
我已经试过了 :
<div v-for="post in posts" :key="post.id">
<h2>{{ post.exercises.id }}</h2>
<h2>{{ post.exercises.name }}</h2>
</div>
你很亲近! :)
<script setup>
import { ref, onBeforeMount } from 'vue'
const posts = ref([])
onBeforeMount(async () => {
posts.value = await fetch("https://private-922d75-recruitmenttechnicaltest.apiary-mock.com/customexercises/").then(raw => raw.json()).then(json => json.exercises)
})
</script>
<template>
<div v-for="post in posts" :key="post.id">
<h2>{{ post.id }}</h2>
<h2>{{ post.name }}</h2>
</div>
</template>
根据 API 响应,exercises
是一个对象数组。因此,要访问它的对象属性,您必须遍历 exercises
数组。
演示:
const app = new Vue({
el: '#app',
data() {
return {
posts: {
exercises:[{
id: "5c10de5792437a5c67e74ba2",
name: "Pull Up",
}, {
id: "5c0e7f6d41403b024ad987cc",
name: "Barbell Bicep Curl",
}]
}
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div v-for="post in posts.exercises" :key="post.id">
<h2>{{ post.id }}</h2>
<h2>{{ post.name }}</h2>
</div>
</div>
您好,我是 Vue 新手,如何在我的模板中遍历它并呈现它? 我可以控制台记录所有内容,但无法在我的页面上呈现它。
API URL : https://private-922d75-recruitmenttechnicaltest.apiary-mock.com/customexercises/
我已经试过了 :
<div v-for="post in posts" :key="post.id">
<h2>{{ post.exercises.id }}</h2>
<h2>{{ post.exercises.name }}</h2>
</div>
你很亲近! :)
<script setup>
import { ref, onBeforeMount } from 'vue'
const posts = ref([])
onBeforeMount(async () => {
posts.value = await fetch("https://private-922d75-recruitmenttechnicaltest.apiary-mock.com/customexercises/").then(raw => raw.json()).then(json => json.exercises)
})
</script>
<template>
<div v-for="post in posts" :key="post.id">
<h2>{{ post.id }}</h2>
<h2>{{ post.name }}</h2>
</div>
</template>
根据 API 响应,exercises
是一个对象数组。因此,要访问它的对象属性,您必须遍历 exercises
数组。
演示:
const app = new Vue({
el: '#app',
data() {
return {
posts: {
exercises:[{
id: "5c10de5792437a5c67e74ba2",
name: "Pull Up",
}, {
id: "5c0e7f6d41403b024ad987cc",
name: "Barbell Bicep Curl",
}]
}
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div v-for="post in posts.exercises" :key="post.id">
<h2>{{ post.id }}</h2>
<h2>{{ post.name }}</h2>
</div>
</div>