【问题标题】:Load ChartJS via VueJS - ChartJS empty and 0px dimension通过 VueJS 加载 ChartJS - ChartJS 为空且尺寸为 0px
【发布时间】:2016-01-13 10:46:28
【问题描述】:

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

基本上它正在工作,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>

【问题讨论】:

    标签: chart.js vue.js


    【解决方案1】:

    您关注this issue。您的图表不会呈现,因为正如您所指出的,该图表的高度和宽度为 0。 我在使用标签集时有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
     };
    }]);
    

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-09
      • 2018-11-11
      • 2018-12-30
      相关资源
      最近更新 更多