本文归柯三(kesan)全部,转载请注明出处 http://www.javashuo.com/article/p-elgbhctr-ck.htmlvue
系统中已经安装以下组件node
npm install echarts
在组件源码处引入echarts组件webpack
import echarts from 'echarts'
若是须要按需引入,请参考官方文档
点此查看官方文档web
先定义一个宽高均为500px的div以供echarts绘出组件vue-cli
<template> <div> <div id="test" style="width:500px;height:500px"> </div> </div> </template>
定义组件须要的属性
在本例中,咱们定义了两个须要由用户来提供数据的属性npm
props: { 'xData': Array, 'yData': Array }
初始化柱形图组件echarts
首先咱们须要定义柱形图的option (title也能够抽出来设置为属性)函数
option: { title: { text: 'Vue柱形图组件' }, xAxis: { type: 'category', data: [] }, yAxis: { type: 'value' }, series: [ { name: '销量', type: 'bar', data: [] } ] }
** 初始化组件 **this
this.chart = echarts.init(document.getElementById("test")) this.option.xAxis.data = this.xData this.option.series[0].data = this.yData this.chart.setOption(this.option)
首先来看一看著名的Vue生命周期图:
很显然在Created时组件都还没渲染,所以比较合适的时机是在mounted完成以后执行ECharts组件初始化的操做。
也就是说咱们要将ECharts初始化工做放到mounted函数中执行,若是放入到Created中就会出错,由于Created时组件还未进行渲染工做。
<template> <div> <div id="test" style="width:500px;height:500px"> </div> </div> </template> <script> /* eslint-disable */ import echarts from 'echarts' export default { name: 'Histogram', data: function () { return { option: { title: { text: 'Vue柱形图组件' }, xAxis: { type: 'category', data: [] }, yAxis: { type: 'value' }, series: [ { name: '销量', type: 'bar', data: [] } ] }, chart: {} } }, props: { 'xData': Array, 'yData': Array }, methods: { updateData: function () { console.log("update data") } }, created: function (){ console.log(this.xData) console.log('created') }, mounted: function(){ this.chart = echarts.init(document.getElementById("test")) this.option.xAxis.data = this.xData this.option.series[0].data = this.yData this.chart.setOption(this.option) } } </script>
Vue.component('组件名', 组件)