从rest api填充Vue模板组件中的表

时间:2016-12-21 19:29:45

标签: vue-component vue.js axios

我有一个Vue组件,我试图让rest api(使用axios)数据填充表格。其余的调用返回chrome中的有效json字符串。但是,我无法在模板中填充表格。当我运行视图时,我在其余的调用中收到以下错误:

  

TypeError:无法设置属性' course'未定义的

这是返回的json:

  

[{" CourseId":"结构"" AUTHORID":"科里内部""名称&#34 ;:"架构   应用"," CourseLength":" 4:20","类别":"软件架构   测试"}]

这是我的模板:

<template>
  <div class="course-list-row">
    <tr v-for="course in courses">
        <td>{{ course.CourseId }}</td>
        <td>{{ course.AuthorId }}</td>
        <td>{{ course.Title }}</td>
        <td>{{ course.CourseLength }}</td>
        <td>{{ course.Category }}</td>
    </tr>
  </div>
</template>

<script>
  import axios from 'axios'
  export default {
    name: 'course-list-row',
    mounted: function () {
      this.getCourses()
      console.log('mounted: got here')
    },
    data: function () {
      return {
        message: 'Course List Row',
        courses: []
      }
    },
    methods: {
      getCourses: function () {
        const url = 'https://server/CoursesWebApi/api/courses/'
        axios.get(url, {
          dataType: 'json',
          headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
          },
          mode: 'no-cors',
          credentials: 'include'
        })
        .then(function (response) {
          console.log(JSON.stringify(response.data))
          this.courses = JSON.stringify(response.data)
        })
        .catch(function (error) {
          console.log(error)
        })
      }
    }
  }
</script>

修改

看来&#34;这个&#34; api回调函数中的this.courses未定义。

1 个答案:

答案 0 :(得分:3)

如您所编辑的那样,您收到了正确的错误,axios.get内的范围发生了变化,您需要进行以下更改:

methods: {
  getCourses: function () {
    var self = this
    const url = 'https://server/CoursesWebApi/api/courses/'
    axios.get(url, {
      dataType: 'json',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      mode: 'no-cors',
      credentials: 'include'
    })
    .then(function (response) {
      console.log(JSON.stringify(response.data))
      self.courses = response.data
    })
    .catch(function (error) {
      console.log(error)
    })
  }
}