Base encapsulation of Echarts
I am writing a blog for the first time to share my encapsulation of Echarts in the development, so that the configuration of the diagrams in the project can be saved in the form of components, which is more convenient for later maintenance.
First, paste the code directly
// BaseEcharts.vue <template> <div ref="echart"></div> </template> <script> import echarts from 'echarts' import { AddListener, removeListener} from 'resize detector' import {debounce} from 'lodash' //resize time is triggered several times, Export default {props: {option: {type: Object, default: () => {}}}, watch: {option: { handler(val) { this.chart.setOption(val) }, deep: Create () {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>Copy the code
The main library used in encapsulation
- The resize Detector is mainly used to detect changes in the browser screen. When the screen changes, call the Resize method of Echarts to change the chart size. Then remember to destroy. And cancel the listening event, so that the two pieces of code will not be separated, readable better
addListener(this.$refs.echart, this.resize)
this.$once('hook:beforeDestroy', () => {
removeListener(this.$refs.echart, this.resize)
this.destroy()
})
Copy the code
- Loadsh mainly uses the anti-shake function. When the screen changes once, multiple resize events will be triggered. To solve performance problems, reference the anti-shake function
created() {
this.resize = debounce(this.resize, 300)
},
Copy the code
The specific use
// 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>
Copy the code