VueJS不呈现表数据

时间:2020-01-11 16:23:49

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

我想从以前使用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"
    },
}

2 个答案:

答案 0 :(得分:1)

由于您尝试访问不存在的属性,它可能无提示地无法呈现。

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

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

答案 1 :(得分: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沙箱项目(查找与您的HelloWorld.vue文件相对应的Courses.vue文件)

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