前几天在vue项目中用到了echarts,通过一段时间的摸索,在此作一总结:vue
在已经引入jQuery的前提下:npm
一、引入依赖包echarts
npm install echarts -S
或dom
npm install -g cnpm --registry=https://registry.npm.taobao.org cnpm install echarts -S
二、建立图表函数
(1)全局引入ui
main.js:this
// 引入echarts import echarts from 'echarts' Vue.prototype.$echarts = echarts
Hello.vuespa
<div id="myChart" :style="{width: '300px', height: '300px'}"></div>
export default { name: 'hello', data () { return { msg: 'Welcome to Your Vue.js App' } }, mounted(){ this.drawLine(); }, methods: { drawLine(){ // 基于准备好的dom,初始化echarts实例 let myChart = this.$echarts.init(document.getElementById('myChart')) // 绘制图表 myChart.setOption({ title: { text: '在Vue中使用echarts' }, tooltip: {}, xAxis: { data: ["衬衫","羊毛衫","雪纺衫","裤子","高跟鞋","袜子"] }, yAxis: {}, series: [{ name: '销量', type: 'bar', data: [5, 20, 36, 10, 10, 20] }] }); } } }
注意: 这里echarts初始化应在钩子函数mounted()中,这个钩子函数是在el 被新建立的 vm.$el 替换,并挂载到实例上去以后调用prototype
(2)按需引入code
上面全局引入会将全部的echarts图表打包,致使体积过大,因此我以为最好仍是按需引入。
Hello.vue
// 引入基本模板 let echarts = require('echarts/lib/echarts') // 引入柱状图组件 require('echarts/lib/chart/bar') // 引入提示框和title组件 require('echarts/lib/component/tooltip') require('echarts/lib/component/title') export default { name: 'hello', data() { return { msg: 'Welcome to Your Vue.js App' } }, mounted() { this.drawLine(); }, methods: { drawLine() { // 基于准备好的dom,初始化echarts实例 let myChart = echarts.init(document.getElementById('myChart')) // 绘制图表 myChart.setOption({ title: { text: 'ECharts 入门示例' }, tooltip: {}, xAxis: { data: ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"] }, yAxis: {}, series: [{ name: '销量', type: 'bar', data: [5, 20, 36, 10, 10, 20] }] }); } } }
三、页面展现