对Echarts进行基础封装
第一次写博客,分享一下自己在开发中对Echarts的封装,这样可以使得项目中图表的配置以组件的形式存在,更加方便后期维护,话不多说,开搞 !!!
先直接贴代码
<template>
<div ref="echart"></div>
</template>
<script>
import echarts from 'echarts'
import { addListener, removeListener } from 'resize-detector'
import { debounce } from 'lodash'
export default {
props: {
option: {
type: Object,
default: () => {}
}
},
watch: {
option: {
handler(val) {
this.chart.setOption(val)
},
deep: true
}
},
created() {
this.resize = debounce(this.resize, 300)
},
mounted() {
this.renderChart()
addListener(this.$refs.echart, this.resize)
this.$once('hook:beforeDestroy', () => {
removeListener(this.$refs.echart, this.resize)
this.destroy()
})
},
methods: {
resize() {
this.chart.resize()
},
renderChart() {
this.chart = echarts.init(this.$refs.echart)
this.chart.setOption(this.option)
},
destroy() {
this.chart.dispose()
this.chart = null
}
}
}
</script>
封装中主要用到了的库
- resize-detector 主要用于检测浏览器屏幕的变换,当屏幕变化时调用echarts的resize方法,从而改变图表大小,然后记得销毁,调用echarts的destroy方法,这里有一个骚操作就是通过hook监听组件销毁钩子函数,并取消监听事件,这样写不会将两段代码分开,可读性较好
addListener(this.$refs.echart, this.resize)
this.$once('hook:beforeDestroy', () => {
removeListener(this.$refs.echart, this.resize)
this.destroy()
})
- loadsh 主要用到了防抖函数,当屏幕变化一次会触发多次的resize事件,为解决性能问题,引用防抖
created() {
this.resize = debounce(this.resize, 300)
},
具体使用
// BsaeLine.vue
<template>
<BaseEchart ref="echart" class='demo_div' :option="options"/>
</template>
<script>
import BaseEchart from './BaseEcharts'
export default {
components: {
BaseEchart
},
data() {
return {
options: {
xAxis: {
type: 'category',
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
},
yAxis: {
type: 'value'
},
series: [
{
data: [820, 932, 901, 934, 1290, 1330, 1320],
type: 'bar'
}
]
}
}
},
}
</script>
<style>
.demo_div {
width: 100%;
height: 100%;
}
</style>
这样可以将项目中的各类图表的options单独设置在文件中
—————————————————————华丽而不失诙谐的分割线——————————————————————
第一次写博客,供参考,如有不对之处,望技术大佬不吝指点