vue統合chartjs

2276 ワード

インストラクション
このコマンドの役割はdomレンダリング後にトリガーされます.vue以外のプラグインにはdomが存在する必要がある場合があります.
Vue.directive('loaded-callback', {
  inserted: function (el, binding, vnode) {
    binding.value(el, binding, vnode)
  }
})

chartjsのインストール
npm install chart.js --save

chartjsコンポーネント


require('chart.js')
export default{
    name: 'components-base-chartjs',
    props: {
        'data': {},
        'options': {},
        'type': {}
    },
    data:function(){
        return {
            canvas: null,
            chart: null
        }
    },
    watch:{
        canvas: function () { // chart       
            this.initChart()
        },
        data: {
            handler: function () { //        
                this.updateChart()
            },
            deep: true
        }
    },
    destoryed:function (){
        if(this.cahrt){
            this.cahrt.destroy()
        }
    },
    computed: {
        currentOptions: function (){
            var options = {}
            if(this.options){ //          
                for(var i in this.options){
                    options[i] = this.options[i]
                }
            }
            return options
        }
    },
    methods: {
        setCanvas: function(el){ // dom     
            this.canvas = el
        },
        initChart: function () { //   chart  
            if(this.data && this.currentOptions){ //        
                this.chart = new Chart(this.canvas.getContext('2d'),{
                    type: this.type,
                    data: this.data,
                    options: this.currentOptions
                })
            }
        },
        updateChart: function () { //   chart  
            this.chart.data = JSON.parse(JSON.stringify(this.data))
            this.chart.update()
        }
    }
}

使用法

optionsおよびデータ構造
ジャンプしてください