2016-12-21 3 views
5

У меня есть компонент Vue, где я пытаюсь получить данные api (используя данные axios) для заполнения таблицы. Второй вызов возвращает допустимую строку json в chrome. Однако я не могу заставить его заполнить таблицу в шаблоне. Когда я бегу взгляд, я получаю следующее сообщение об ошибке при вызове отдыха:Таблица заполнения в компоненте шаблона Vue из rest api

TypeError: Cannot set property 'courses' of undefined

Вот 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> 

Редактировать:

Похоже на это «this» of this.courses в api ca Функция llback не определена.

ответ

2

как вы редактировали, вы получили правильную ошибку, объем этого изменилось внутри 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) 
    }) 
    } 
} 
+1

Это он! Благодарю. Мне также пришлось удалить json.stringify, но это было скорее след и ошибка. – steveareeno