1

我将echarts封装成了一个全局组件,因为很多其他都用到了,接收一个配置项参数,并且按需引入。

为了让图表能够随着屏幕宽度自适应,通过 element-resize-detector监听dom元素的变化。
而且还能随着左侧边栏的收缩而变化

安装依赖

npm install echarts --save
npm install element-resize-detector  

echarts.vue 文件

this.$el 代表的是当前组件的dom元素
子组件中不需要实例化echarts对象,请求接口的时候通过父组件调用子组件的init()方法
<template>
  <div></div>
</template>

<script>
import * as echarts from 'echarts'

// 监听dom元素的变化
import elementResizeDetectorMaker from 'element-resize-detector'

// echarts导入相关
import { GridComponent, TitleComponent, TooltipComponent, LegendComponent } from 'echarts/Components'
import { BarChart, PieChart, LineChart } from 'echarts/charts'
import { UniversalTransition } from 'echarts/features'
import { CanvasRenderer } from 'echarts/renderers'

echarts.use([
  GridComponent, 
  TitleComponent,   // 标题
  TooltipComponent, // 鼠标移入提示
  LegendComponent,  // 图例 
  BarChart,     // 柱状图
  PieChart,     // 饼图
  LineChart,    // 折线图
  UniversalTransition,
  CanvasRenderer
])
export default {
  name:'dyEcharts',
  pops:['option'],
  data(){
      return {
          mychart:''
      } 
  },

  methods:{
    init(){
      if (this.mychart){
        this.mychart.dispose()
      }
      this.mychart = echarts.init(this.$el)
      this.mychart.resize()
      this.option && this.mychart.setOption(this.option)

      // 监听盒子宽度的变化进行重置大小
      let erd = elementResizeDetectorMaker()
      erd.listenTo(this.$el,e => {
        this.$nextTick(() => {
          this.mychart.resize()
        })
      })
    }
  }
}
</script>

页面中使用echarts组件

template中

<template>
  <div>
    <!-- 折线图 -->
    <div class="line">
      <dyEcharts :option='LineOption'
                 ref="line"
                 style="height:300px"></dyEcharts>
    </div>

    <!-- 柱状图 -->
    <div class="Bar">
      <dyEcharts :option='BarOption'
                 ref="bar"
                 style="height:300px"></dyEcharts>
    </div>
  </div>
</template>

script中

import {lineApi,barApi} from '@/api/echarts'  // 请求接口

data(){
  retutn {
    lineOption:[],
    barOption:[],
  }
},
methods:{
    line(){
      lineApi({}).then(res=>{
        /* 
        对echarts的配置项option进行处理
        ......
        */
       
       // 配置好option后,执行子组件echarts中的init方法
       this.$nextTick(() => {
         this.$refs.line.init()
       })
      })
    }
}

菜鸟前端
10 声望0 粉丝