1.目标:
封装一个好用的echarts的vue2组件,方便使用,1.自动resize.2.使用便捷。
<template>
<div ref="chart" :style="{width: '100%', height: '100%'}"></div>
</template>
<script>
import echarts from 'echarts'
export default {
name: 'ECharts',
props: {
options: {
type: Object,
default: () => ({})
},
autoResize: {
type: Boolean,
default: true
}
},
data() {
return {
chart: null
}
},
mounted() {
this.initChart()
if (this.autoResize) {
window.addEventListener('resize', this.handleResize)
}
},
beforeDestroy() {
if (this.autoResize) {
window.removeEventListener('resize', this.handleResize)
}
if (this.chart) {
this.chart.dispose()
}
},
methods: {
initChart() {
this.chart = echarts.init(this.$refs.chart)
this.chart.setOption(this.options)
},
handleResize() {
if (this.chart) {
this.chart.resize()
}
}
},
watch: {
options(newOptions) {
this.chart.setOption(newOptions)
}
}
}
</script>
2.使用
<template>
<div>
<e-charts :options="chartOptions" :auto-resize="true"></e-charts>
</div>
</template>
<script>
import ECharts from '@/components/ECharts'
export default {
components: { ECharts },
data() {
return {
chartOptions: {
// 图表配置选项...
}
}
}
}
</script>