问题描述:

Alright, so I am trying to create a ChartJS instance via VueJS so that I could easily update its data via AJAX requests inside the component.

Basically it is working, the ChartJS instance gets created but it is empty and has a height and width of 0 and when I resize it via console it is still empty.

So what would be the best way of creating a "ChartJS Component" with VueJS or where is the fault in my code below?


The very basic way I want to load chart is like this.

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

This is the basic component

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 is the directive which I use to pass down the data from the component. I do it this way to get this.el so that I can get the Context of it

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

});

This is the template of the component

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

网友答案:

You are concerned by this issue. Your graph does not render because, as you pointed out, the graph has a height and width of 0. I had this problem while working with tabsets, and I solved it by redrawing the graph with a directive like this :

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
 };
}]);

Hope this can help you

相关阅读:
Top