1、具体封装
1、图表组件文件
实现echarts公共的功能:实例的创建、销毁,异步数据的加载与动态更新,屏幕大小自适应
图表具体配置由options参数传入
<template>
<div ref="main" class="echart"> </div>
</template>
<script>
export default {
name: 'echarts',
props: {
options: {
type: Object
}
},
data () {
return {
myChart: null
}
},
watch: {
options () {
this.setOptionChart()
},
deep: true
},
mounted () {
this.initChart()
// import _ from 'lodash'
this.eventresizeEchart = _.debounce(this.resizeEchart, 500)
window.addEventListener("resize", this.eventresizeEchart);
},
beforeDestroy () {
window.removeEventListener("resize", this.eventresizeEchart)
this.myChart?.dispose()
},
methods: {
resizeEchart () {
// 屏幕自适应
this.myChart?.resize?.()
},
initChart () {
this.myChart = this.$echarts.init(this.$refs.main);
this.setOptionChart()
},
setOptionChart () {
this.myChart.setOption(
this.options
);
}
}
}
</script>
<style lang="less" scoped>
.echart {
width: 100%;
height: 100%;
}
</style>
2、图表配置文件
允许传入所需配置的数据
// 导入的数据data
const lineOption = data => {
// 图表配置对象defaultConfig
const defaultConfig = {
//配置信息
}
return defaultConfig
}
export default { lineOption }
3、自动导入配置文件
利用require.context实现工程的自动化
// 实现工程自动化
const modulesFiles = require.context('./options', false, /^.*\.js$/) // 遍历options文件夹内的.js文件
let fileList = {}
modulesFiles.keys().forEach(item => {
fileList = Object.assign({}, fileList, modulesFiles(item).default)
})
// fileList = {
// lineOption: defaultConfig // line.js的文件配置
// ...
// ...
// }
export default fileList
4、使用
1、在main中导入配置文件
import options from './components/charts/index'
Vue.prototype.$echartOptions = options // echart 自动化加载配置
2、使用echarts组件
<echarts :options='option'></echarts>
computed: {
option () {
//this.echartData echarts数据
return this.$echartOptions.lineOption(this.echartData)
},
}
2、按需引用
import Vue from 'vue'
// 引入 echarts 核心模块,核心模块提供了 echarts 使用必须要的接口。
import * as echarts from 'echarts/core'
// 引入柱状图图表,图表后缀都为 Chart
import { LineChart } from 'echarts/charts'
// 引入提示框,标题,直角坐标系,数据集,内置数据转换器组件,组件后缀都为 Component
import { TitleComponent, TooltipComponent, GridComponent, DatasetComponent, TransformComponent, LegendComponent } from 'echarts/components'
// 标签自动布局,全局过渡动画等特性
import { LabelLayout, UniversalTransition } from 'echarts/features'
// 引入 Canvas 渲染器,注意引入 CanvasRenderer 或者 SVGRenderer 是必须的一步
import { CanvasRenderer } from 'echarts/renderers'
// 注册必须的组件
echarts.use([TitleComponent, TooltipComponent, GridComponent, DatasetComponent, TransformComponent, LineChart, LabelLayout, UniversalTransition, CanvasRenderer, LegendComponent])
Vue.prototype.$echarts = echarts