摆脱echart要id的限制

发布时间 2023-05-16 16:43:35作者: 张德政

引言

最近的开发中,我想对echart做二次封装,因为实际开发会有很多相同的内容,如柱形图的legend的位置、grid的分割线等,没必要每次都写一遍。

根据echart官方示例,要通过id获取节点,交给echart做初始化。如图

image

方案的产生

我在想,document.getElementById本质还是去获取真实dom节点,而vue中是可以通过ref的方式获取dom节点的,顺着这个思路,我尝试了下,不出意外,果真可以。在对echart进行二次封装时,id就没必要让使用者每次都传个不一样的进来。这里就能解决这个问题。

<template>
  <div ref="echart" class="chart-in">
  </div>
</template>

这里是直接获取ref的,不需要再去设置id,免去多余的一步。

  mounted() {
    this.chart = echarts.init(this.$refs.echart); // here!!!
    this.reflesh([]);
    this.$once('hook:beforeDestroy', () => { this.chart.dispose(); });
  },