javascript - VueJS不渲染表格数据

标签 javascript html vue.js vuejs2 vue-component

我想渲染我之前使用 VueJS 2 创建的 API 中的数据。我的 VueJS 代码块不会渲染我通过后端服务发送的数据。调试控制台不返回任何错误。 Firefox 的 Vue 调试扩展成功返回表数据。但我无法在 HTML 表格中显示数据。这是代码块:

Courses.vue 文件:

<template>
  <div class="container">
    <h3>Courses:</h3>
    <table class="table">
      <thead>
        <tr>
          <th scope="col">Id</th>
          <th scope="col">Name</th>
          <th scope="col">Language</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="course in courses" v-bind:key="course.ID"> 
          <th scope="row">{{course.ID}}</th>
          <td>{{course.name}}</td>
          <td>{{course.language}}</td>
        </tr>
      </tbody>
    </table> 
  </div> 
</template>

<script>
  import axios from 'axios';

  export default {
    name: 'Courses',
    data() {
      return {
        courses: null,
      };
    },
    created: function() {
      axios
        .get('http://localhost:8080/api/index')
        .then(res => {
          this.courses = res.data;
        })
    }
  }
</script>

<style>
  h3 {
    margin-bottom: 5%;
  }
</style>

App.vue 文件:

<template>
  <div id="app">
    <Courses />
  </div>
</template>

<script>
import Courses from './components/Courses.vue'

export default {
  name: 'app',
  components: {
    Courses
  }
}
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

我的 API 结果:

// 20200111185700
// http://localhost:8080/api/index

{
  "Courses": [
    {
      "ID": 16,
      "Name": "Math",
      "Language": "en"
    },
    {
      "ID": 15,
      "Name": "Biology",
      "Language": "en"
    },
}

最佳答案

API 结果的格式似乎不正确。您在类(class)数据周围缺少 ] 括号。

我认为它应该看起来像这样

{
  "Courses": [
    {
      "ID": 16,
      "Name": "Math",
      "Language": "en"
    },
    {
      "ID": 15,
      "Name": "Biology",
      "Language": "en"
    },
   ],
}

另请注意,当您从网络返回响应时,您应该返回类(class),而不仅仅是直接返回数据。这就是你的 vue 模板被配置为读取数据的方式。

这个this.courses = res.data;变成this.courses = res.data.Courses;

此外,尝试将类(class)属性命名为全部小写单词,因为这正是模板正在寻找的内容。

这是解决您的问题的示例 vue 沙箱项目(查找与您的 Courses.vue 文件对应的 HelloWorld.vue 文件)

https://codesandbox.io/s/inspiring-swirles-lq6s4?fontsize=14&hidenavigation=1&theme=dark

关于javascript - VueJS不渲染表格数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59696298/

相关文章:

javascript - Redux-form 从表单实例内部访问表单的值

html - 如何禁用 CSS 垂直菜单弹出效果

vue.js - 如何将进度条添加到 vue-strap 轮播 slider ?

javascript - 使用 JS 禁用选项

javascript - 如何垂直对齐具有不同高度的div?

javascript - 导航菜单消失,直到调整窗口大小

javascript - Jquery Resizable 将 DIV 高度降低到小于默认值(即将 minHeight 降低到大约 1px)

javascript - vue中如何绑定(bind)数组对象?

javascript - 如何在 VueJs 中重用 ViewModel?

javascript - 更改 HTML 模板中的 javascript 函数名称或元素 ID 会使其停止工作