【问题标题】:VueJS does not render table dataVueJS 不渲染表格数据
【发布时间】:2020-04-28 23:12:08
【问题描述】:

我想从我之前使用 VueJS 2 创建的 API 呈现数据。我的 VueJS 代码块不呈现我通过后端服务发送的数据。调试控制台不返回错误。 Firefox 的 Vue Debug 扩展成功返回表数据。但我无法在 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"
    },
}

【问题讨论】:

    标签: javascript html vue.js vuejs2 vue-component


    【解决方案1】:

    API 结果的格式似乎不正确。您在课程数据周围缺少] 括号。

    我觉得应该是这个样子

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

    另请注意,当您从网络收到回复时,您应该返回课程,而不仅仅是直接返回数据。这就是您的 vue 模板被配置为读取数据的方式。

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

    此外,请尝试将课程属性命名为全部小写,因为这是模板要查找的内容。

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

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

    【讨论】:

      【解决方案2】:

      它可能会静默渲染失败,因为您尝试访问不存在的属性。

      确保 course.namecourse.language 实际上不应该是大写(course.Namecourse.Language

      <td>{{course.Name}}</td>
      <td>{{course.Language}}</td>
      

      【讨论】: