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

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

装置依赖

npm install echarts --savenpm install element-resize-detector  

echarts.vue 文件

this.$el 代表的是以后组件
子组件中不须要实例化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'],  methods:{    init(){      const myChart = echarts.init(this.$el)      myChart.resize()      this.option && myChart.setOption(this.option)      // 监听盒子宽度的变动进行重置大小      let erd = elementResizeDetectorMaker()      erd.listenTo(this.$el,e => {        this.$nextTick(() => {          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()       })      })    }}