2015-10-15 35 views
1

好吧,所以我想通過VueJS創建一個ChartJS實例,這樣我就可以輕鬆地通過組件內部的AJAX請求更新其數據。通過VueJS加載ChartJS - ChartJS空和0px尺寸

基本上它工作,ChartJS實例被創建,但它是空的,並有一個高度和寬度爲0,當我通過控制檯調整它,它仍然是空的。

那麼用VueJS創建「ChartJS組件」的最佳方式是什麼?或者我的代碼中的錯誤在哪裏?


我想加載圖表的最基本的方式就是這樣。

<chart :resource="'https://httpbin.org/get'"></chart> 

這是基本的成分

var Vue = require('vue'); 

Vue.component('chart', { 
    template: require('./template.html'), 
    props: ['resource'], 
    data: function() { 
     return { 
      startingData: {}, 
      latestLabel: {}, 
     } 
    }, 
    ready: function() { 
     // here I would load the js data and set the startingData 
    }, 
}); 

這是我使用從部件向下傳遞數據的指令。我做這種方式來獲得this.el,這樣我可以得到它

Vue.directive('loadData', function(value) { 
    var startingData = { 
      labels: [1, 2, 3, 4, 5, 6, 7], 
      datasets: [{ 
       fillColor: "rgba(151,187,205,0.2)", 
       strokeColor: "rgba(151,187,205,1)", 
       pointColor: "rgba(151,187,205,1)", 
       pointStrokeColor: "#fff", 
       data: [28, 48, 40, 19, 86, 27, 90] 
      }] 
     }, 
     latestLabel = startingData.labels[6]; 

    var liveChart = new Chart(this.el.getContext('2d')).Bar(startingData); 

    setInterval(function() { 
     liveChart.addData([Math.random() * 100], ++latestLabel); 
     liveChart.removeData(); 
    }, 1000); 
}); 

方面,這是組件

<canvas width="960" height="300" v-load-data="startingData"></canvas> 

回答

1

你被this issue有關的模板。您的圖形不會呈現,因爲,正如你所指出,該圖具有的高度和0 我this problem與tabsets工作時的寬度,我用這樣的指令重新繪製圖形解決它:

app.directive('graphCanvasRefresh', ['$compile', function($compile) { 
function link(scope, elem, attrs) { 

function refreshDOM() { 
    var markup = '<canvas class="chart chart-pie" id="graph" data="entityGraph.data" labels="entityGraph.labels" legend="true" colours="graphColours" ></canvas>'; 
    var el = angular.element(markup); 
    compiled = $compile(el); 
    elem.html(''); 
    elem.append(el); 
    compiled(scope); 
}; 

// Refresh the DOM when the attribute value is changed 
scope.$watch(attrs.graphCanvasRefresh, function(value) { 
    refreshDOM(); 
}); 

// Clean the DOM on destroy 
scope.$on('$destroy', function() { 
    elem.html(''); 
}); 
}; 

    return { 
    link: link 
}; 
}]); 

希望這可以幫到你