通过VueJS加载ChartJS - ChartJS为空且0px维度

时间:2015-10-15 05:40:47

标签: chart.js vue.js

好吧,所以我试图通过VueJS创建一个ChartJS实例,以便我可以通过组件内部的AJAX请求轻松更新其数据。

基本上它正在工作,ChartJS实例被创建但是它是空的并且高度和宽度为0,当我通过控制台调整它时它仍然是空的。

那么创建一个" ChartJS组件的最佳方式是什么呢?使用VueJS或我的代码中的错误在哪里?

我想加载图表的基本方法是这样的。

<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 个答案:

答案 0 :(得分:1)

您对this issue感到担忧。您的图形不会渲染,因为正如您所指出的,图形的高度和宽度为0。 在使用tabset时我有this problem,我通过使用如下指令重新绘制图形来解决它:

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

希望这可以帮到你