我无法显示 Vue 中使用 fetch() 从快速服务器获取的对象数组;数据的获取有效,但我不确定如何在 html 中显示它。下面是成功从 Express 获取 JSON 的 Vue 代码。
computed: {
async fetchData() {
fetch('http://localhost:4000/lessons').then(
function (response) {
response.json().then(
function (json) {
this.lessons = json;
console.log(this.lessons)
});
})
},
}
console.log 成功显示了获取的对象数组,但未以 HTML 格式显示。以下是未显示获取的对象数组的 HTML 代码。
<div v-for="lesson in fetchData" class="card">
<h2 v-text ="lesson.subject"></h2>
<figure>
<img v-bind:src="lesson.image">
</figure>
<p>Location: {{lesson.location}}</p>
<p>Price: £{{lesson.price}}</p>
<p>Description: {{lesson.description}}</p>
<p>Maximum Class Size: {{lesson.maximumSpaces}} People</p>
</div>
如何才能在 HTML 文件中显示对象数组?感谢您的宝贵时间。
最佳答案
有几个问题:1) 计算不是异步的。 2) 模板不是异步的,因此您甚至无法以这种方式调用异步方法。 3) 你的 fetch
回调函数应该是一个箭头函数或者它注入(inject)它自己的 this
并阻止数据设置。 4) 使用 :key
和 v-for
。这是一个正确的模式,使用一种方法来获取数据:
methods: {
async fetchData() {
const response = await fetch('http://localhost:4000/lessons');
this.lessons = await response.json();
}
}
您可以在created
或mounted
生命周期钩子(Hook)或其他地方调用它:
data: () => ({
lessons: []
}),
created() {
this.fetchData()
}
然后遍历数据:
<div v-for="(lesson, index) in lessons" class="card" :key="index">
...
</div>
这是一个演示:
new Vue({
el: "#app",
data: () => ({
lessons: []
}),
created() {
this.fetchData()
},
methods: {
async fetchData() {
const response = await fetch('https://jsonplaceholder.typicode.com/todos');
this.lessons = await response.json();
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div v-for="(lesson, index) in lessons" :key="index">
{{ lesson }}
</div>
</div>
关于javascript - 在 HTML 中显示 Vue 计算对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65569870/