【问题标题】:Populate table in Vue template component from rest api从 rest api 填充 Vue 模板组件中的表
【发布时间】:2017-05-07 08:01:10
【问题描述】:

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

TypeError: 无法设置未定义的属性“课程”

这是返回的 json:

[{"CourseId":"architecture","AuthorId":"cory-house","Title":"Architecting 应用程序","CourseLength":"4:20","Category":"软件架构 测试"}]

这是我的模板:

<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>

编辑:

api回调函数中this.courses的“this”好像是未定义的。

【问题讨论】:

    标签: vue-component vue.js axios


    【解决方案1】:

    正如你编辑的那样,你得到了正确的错误,这个范围在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)
        })
      }
    }
    

    【讨论】:

    • 就是这样!谢谢。我还必须删除 json.stringify 但这更像是一个跟踪和错误的事情。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-14
    • 1970-01-01
    • 2022-09-06
    • 2021-03-28
    • 1970-01-01
    • 2020-12-12
    • 1970-01-01
    相关资源
    最近更新 更多