ECharts支持webpack引入,图省事可以将ECharts整个引入var echarts = require(‘echarts’);不过ECharts还是不小的,大部分情况只是用到很少一部分功能,我平时习惯于按需引入的。
// 引入 ECharts 主模块var echarts = require('echarts/lib/echarts');// 引入柱状图require('echarts/lib/chart/bar');// 引入提示框和标题组件require('echarts/lib/component/tooltip');require('echarts/lib/component/title');
接下来我们就要在vue中声明初始化ECharts了。因为ECharts初始化必须绑定dom,所以我们只能在vue的mounted生命周期里初始化。
mounted() {this.initCharts();},methods: {this.initCharts() {this.chart = echarts.init(this.$el);this.setOptions();},setOptions() {this.chart.setOption({title: {text: 'ECharts 入门示例'},tooltip: {},xAxis: {data: ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]},yAxis: {},series: [{name: '销量',type: 'bar',data: [5, 20, 36, 10, 10, 20]}]})}}
就这样简单,ECharts就配置完成了,这时候你想说我的data是远程获取的,或者说我动态改变ECharts的配置该怎么办呢?我们可以通过watch来触发setOptions方法
//第一种 watch options变化 利用vue的深度 watcher,options一有变化就重新setOptionwatch: {options: {handler(options) {this.chart.setOption(this.options)},deep: true},}//第二种 只watch 数据的变化 只有数据变化时触发EChartswatch: {seriesData(val) {this.setOptions({series:val})}}
