2016-12-21 30 views
5

Tôi có thành phần Vue nơi tôi đang cố gắng lấy lại dữ liệu api (sử dụng trục) để điền bảng. Cuộc gọi còn lại trả về một chuỗi json hợp lệ trong chrome. Tuy nhiên, tôi không thể đưa nó vào bảng trong mẫu. Khi tôi chạy xem, tôi nhận được lỗi sau trong các cuộc gọi còn lại:Điền bảng trong thành phần mẫu Vue từ phần còn lại api

TypeError: Cannot set property 'courses' of undefined

Đây là json được trả lại:

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

Đây là mẫu của tôi:

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

Chỉnh sửa:

Nó xuất hiện "this" của this.courses trong api ca Hàm llback không xác định.

Trả lời

2

như bạn đã chỉnh sửa, bạn đã có những lỗi chính xác, phạm vi này đã thay đổi bên trong axios.get, bạn cần phải thực hiện những thay đổi sau đây:

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

Đó là nó! Cảm ơn. Tôi cũng đã phải loại bỏ các json.stringify nhưng đó là một dấu vết và điều lỗi. – steveareeno

Các vấn đề liên quan