vue中使用echarts
echarts在后台管理项目中很常见,刚开始使用也是踩了很多坑,本文就图表随窗口大小自适应变化、图表封装成组件、多图表循环等问题进行记录。
一、安装依赖
- npm install echarts -S 或者 npm install echarts --save
二、安装
一般看项目中使用图表类型的多少决定全局安装还是按需引用
- 在main.js中全局安装
第一种方式 引入echarts
import Echarts from 'echarts';
Vue.prototype.echarts = Echarts;
Vue.use(Echarts);
第二种方式引入
import Echarts from 'echarts';
Vue.prototype.$echarts = Echarts;
-
区别在于初始化时是否需要加“$”
第一种方式:
第二种方式:
-
按需引入
在需要引入echarts的组件中依次引入需要的组件
// 引入基本模板
let echarts = require('echarts/lib/echarts')
// 引入柱状图组件
require('echarts/lib/chart/bar')
// 引入提示框和title组件
require('echarts/lib/component/tooltip')
require('echarts/lib/component/title')
三、使用示例(图表自适应)
示例的具体代码就不展示,重点说一下echarts图表自适应问题
mounted() {
this.echartLoad();
//实现自适应
this.resizeEcharts = ()=>{
this.echarts.init(document.getElementById('zuzhi')).resize(); //这里的myChart就是要自适应的图表容器Id
}
window.addEventListener('resize',this.resizeEcharts)
},
//移除事件监听,避免内存泄漏
beforeDestroy() {
window.removeEventListener('resize', this.resizeEcharts)
this.resizeEcharts= null
},
四、多图表循环
项目中有多个表时,可以以组件的形式使用Echarts,在父组件用V-for循环数据,但是echarts的容器只能用“id”,这时就可以用V-for的index参数,示例中模拟的数据比较简单,复杂的数据还需在子组件中处理数据,保证图表的正确渲染。
- 父组件
- 子组件
props接受父组件传下来的数据,通过computed拼接图表id
接下来会继续总结使用遇到Echarts的各种问题~