該指令的做用是dom渲染後觸發,由於非vue的插件有的是dom必須存在的狀況下才能夠執行javascript
Vue.directive('loaded-callback', { inserted: function (el, binding, vnode) { binding.value(el, binding, vnode) } })
npm install chart.js --save
<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>
請跳轉html