javascript - 在 HTML 中显示 Vue 计算对象数组

标签 javascript html arrays json vue.js

我无法显示 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) 使用 :keyv-for。这是一个正确的模式,使用一种方法来获取数据:

methods: {
   async fetchData() {
      const response = await fetch('http://localhost:4000/lessons');
      this.lessons = await response.json();
   }
}

您可以在createdmounted 生命周期钩子(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/

相关文章:

javascript - 使用 routeProvider 的模板的多个 Controller

javascript - HTML 输入字段可自动检索分钟、小时和天的粒度

javascript - 图像拉伸(stretch)和裁剪以适合精确尺寸

html - 在同一行上使用 CSS 省略号和其他元素

javascript - 当 Chrome 中的选项卡处于非事件状态时,如何使 setInterval 也起作用?

javascript - ReactJS Array.push 函数在 setState 中不起作用

javascript - 将 JavaScript 对象的可变长度对象的属性连接到该对象的新属性中

python - C 中的字符串格式化

java - C++将数字添加到数组对象?

javascript - PHP脚本获取数组中的数据库值以在下拉列表中查看