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

ste*_*eno 6 vue.js vue-component axios

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

TypeError:无法设置undefined的属性'courses'

这是返回的json:

[{"CourseId":"architecture","AuthorId":"cory-house","Title":"Architecting Applications","CourseLength":"4:20","Category":"Software Architecture Test"}]

这是我的模板:

<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>
Run Code Online (Sandbox Code Playgroud)

编辑:

看来api回调函数中this.courses的"this"是未定义的.

Sau*_*abh 5

编辑后,您得到了正确的错误,其范围已在内部更改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)
    })
  }
}
Run Code Online (Sandbox Code Playgroud)