2015-03-01 27 views
11

Tôi đang gặp sự cố khi nhận dữ liệu để hiển thị trong các thành phần Vue của mình. Tôi đang sử dụng Vueify và tôi đang cố tải một mảng danh sách từ thành phần listings.vue và tôi vẫn gặp phải lỗi. Ngoài ra, tôi không hiểu cách lấy dữ liệu qua phương thức computed. Bất kỳ trợ giúp sẽ được đánh giá cao.Làm cách nào để hiển thị dữ liệu thông qua các thành phần bằng Vue.js (sử dụng Vueify)?

Đây là lỗi tôi nhận được trong giao diện điều khiển:

[Vue warn]: The "data" option should be a function that returns a per-instance value in component definitions. 
[Vue warn]: $mount() should be called only once. 

Đây là app.vue tôi

// app.vue 
<style> 
    .red { 
    color: #f00; 
    } 
</style> 

<template> 
    <div class="container"> 
     <div class="listings" v-component="listings" v-repeat="listing"></div> 
    </div> 
</template> 

<script> 
    module.exports = { 
     replace: true, 
     el: '#app', 
     components: { 
      'listings': require('./components/listings.vue') 
     } 
    } 
</script> 

Sau đây là thành phần listings.vue tôi

<style> 
.red { 
    color: #f00; 
} 
</style> 

<template> 
    <div class="listing">{{title}} <br> {{description}}</div> 
</template> 

<script> 

    module.exports = { 

      data: { 
      listing: [ 
       { 
       title: 'Listing title number one', 
       description: 'Description 1' 
       }, 
       { 
       title: 'Listing title number two', 
       description: 'Description 2' 
       } 
      ] 
      }, 

     // computed: { 
     // get: function() { 
     //  var request = require('superagent'); 
     //  request 
     //  .get('/post') 
     //  .end(function (res) { 
     //   // Return this to the data object above 
     //    // return res.title + res.description (for each one) 
     //  }); 
     // } 
     // } 
    } 
</script> 

Trả lời

36

Cảnh báo đầu tiên có nghĩa là khi bạn định nghĩa một thành phần, tùy chọn data sẽ giống như sau:

module.exports = { 
    data: function() { 
    return { 
     listing: [ 
      { 
      title: 'Listing title number one', 
      description: 'Description 1' 
      }, 
      { 
      title: 'Listing title number two', 
      description: 'Description 2' 
      } 
     ] 
    } 
    } 
} 

Ngoài ra, không đặt yêu cầu ajax bên trong các thuộc tính được tính, vì các tính toán được đánh giá mỗi lần bạn truy cập giá trị đó.

+3

Vì sao @Evan You? Các tài liệu cũng đề cập đến [cùng một điều] (https://vuejs.org/v2/guide/components.html#data-Must-Be-a-Function) – peter

+0

Tại sao dữ liệu phải được bao bọc trong một hàm và đạo cụ don ' t phải? –

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