echarts自适应封装组件
<template> <div :id="id" :class="className" :style="{ height: height, width: width }" ref="chart"></div> </template> <script> export default { name: 'echart', props: { className: { type: String, default: 'chart', }, id: { type: String, default: 'chart', }, width: { type: String, default: '100%', }, height: { type: String, default: '2.5rem', }, options: { type: Object, default: () => ({}), }, }, data(){ return { chart:null, } }, watch:{ options:{ handler(options){ this.chart.setOption(options,true) }, deep:true } }, mounted(){ this.$nextTick(()=>{ this.chart=this.$echarts.init(this.$el); this.chart.setOption(this.options,true) }) let that=this;
//不能用window.onresize,会导致resize被覆盖,最终只有一个组件能自适应 window.addEventListener('resize',function(){ that.chart&&that.chart.resize() }) }, beforeDestroy(){ this.chart&&this.chart.dispose(); this.chart=null }, methods:{ initChart(){ } } } </script> <style></style>
使用
<Echart id="spBarChart" width="100%" height="200px" :options="lineChartOption3"></Echart> import Echart from '@/components/chart/echart'
结果
实现一个echarts通用组件,当修改浏览器窗口大小的时候,可以自适应
开源中国博客地址:https://my.oschina.net/u/2998098/blog/1540520