【问题标题】:Display Vue Computed Array of Objects in HTML在 HTML 中显示 Vue 计算的对象数组
【发布时间】:2021-04-10 16:05:45
【问题描述】:

我无法显示使用 fetch() 从快速服务器获取的 Vue 对象数组;数据的获取工作,但我不确定如何在 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 文件中显示对象数组?感谢您的宝贵时间。

【问题讨论】:

    标签: javascript html arrays json vue.js


    【解决方案1】:

    有几个问题:1)计算不是异步的。 2)模板不是异步的,所以你甚至不能以这种方式调用异步方法。 3)你的fetch回调函数应该是一个箭头函数或者它注入自己的this并阻止数据设置。 4) 使用:keyv-for。这是一个正确的模式,使用方法来获取数据:

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

    您可以在 createdmounted 生命周期钩子中调用它,或者在其他地方调用它:

    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>

    【讨论】:

    • 还要注意v-for元素应该有键
    猜你喜欢
    • 2017-03-12
    • 2021-09-28
    • 2020-08-11
    • 2020-04-20
    • 2020-06-18
    • 2020-10-19
    • 2019-03-29
    • 2021-02-09
    • 1970-01-01
    相关资源
    最近更新 更多