2017-08-30 50 views
2

,以便檢索來自火力地堡一些數據,並在圖表上顯示它,我使用Vue.js與chart.js之數組。 這是我的代碼:動態填充與火力地堡數據Vue.js

import {Line} from 'vue-chartjs' 

let Firebase = require('firebase'); 
// 
let config = { 
    apiKey: '****************************', 
    authDomain: '****************************', 
    databaseURL: '****************************', 
    storageBucket: '****************************' 
}; 

let firebaseApp = Firebase.initializeApp(config); 
let db = firebaseApp.database(); 
let schools = db.ref('schools'); 

export default Line.extend({ 
    firebase: { 
     schoolsArray: schools 
    }, 
    data(){ 
     alert('data'); 
     return { 
      names: [] 
     } 
    }, 
    computed: { 
     schoolNames: function() { 
      for (let item of this.schoolsArray) { 
       this.names.push(item.name); 
      } 
      alert('computed'); 
      return this.names 
     } 
    }, 

    mounted() { 
     alert('mounted'); 
     this.renderChart({ 
      labels: this.names.toString(), 
      datasets: [{ 
       label: 'School Reports', backgroundColor: '#dd4935', 
       data: [10, 20, 50, 12, 34, 43, 45] 
      }] 
     }, {responsive: true, maintainAspectRatio: true}) 
    } 
}) 

的問題是,陣列始終是空的,不顯示標籤。以下是它的外觀: enter image description here

我需要在x軸上顯示學校名稱!下面

上的圖像的Vue.js調試結果: enter image description here

回答

1

db.ref('school')返回你必須從中檢索的數據「firebase.database.Reference」對象。你可以添加到您的VUE mounted生命週期掛鉤:

db.ref('school').once('value') 
.then((dataSnapshot) => { 
    this.schoolsArray = dataSnapshot.val(); 
}); 

,你也可以使用.on方法,每次將自動觸發回調時,服務器上的數據變化。所以確保在組件被銷燬時將其刪除。 的文檔,請參見:https://firebase.google.com/docs/reference/js/firebase.database.Reference#once

+0

我已經發布了一個更多的圖片,顯示了名稱檢索但在圖上沒有顯示! –

+0

如果你再次在'.once'回調中調用'renderChart'方法有幫助嗎? – user2520818

+0

是的我使用這段代碼進入方法生命週期鉤子並在renderChart之前調用它,但仍然看不到任何標籤o我的圖表 –