vue集成chart.js的实现方法

该指令的作用是dom渲染后触发,因为非vue的插件有的是dom必须存在的情况下才可以执行

Vue.directive('loaded-callback', { inserted: function (el, binding, vnode) { binding.value(el, binding, vnode) } })

安装chartjs

npm install chart.js --save

chartjs 组件

<template> <canvas refs="chartcanvas" v-loaded-callback="setCanvas"></canvas> </template> <script type="text/javascript"> 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() } } } </script>

用法

<chartjs :options="options" type="pie" :data="data"></chartjs>

options 及数据结构

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/f95efc0e625bb0c40714086a11c9009e.html