当前位置:网站首页>Echart simple component packaging

Echart simple component packaging

2022-07-06 18:20:00 Bug pill

echart Simple component encapsulation

<template>
  <div class="chartBox" ref="echartBox"></div>
</template>

<script>
import * as echarts from 'echarts'
export default {
  props: {
​    barData: {
​      type: Array,
​      default: () => []
​    }
  },
  watch: {
​    barData: {
​      handler: function() {
​        this.initChart()
​      },
​      deep: true
​    }
  },
  mounted() {
​    this.initChart()
  },
  methods: {
​    initChart() {
​      const dom = this.$refs.echartBox
​      const myChart = echarts.init(dom)
​      myChart.setOption({
​        xAxis: {
​          type: 'category',
​          data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
​        },
​        yAxis: {
​          type: 'value'
​        },
​        series: [
​          {
​            data: this.barData,
​            type: 'bar'
​          }
​        ]
​      })
​    }
  }
}

</script>
<style scoped>
.chartBox {
  width: 400px;
  height: 300px;
}
</style>

Problems encountered

Packaged echart When components are reused , Warning :

The above code if I will this.$ref Change it to document.querySelector; Then the browser will issue a warning , And only one picture will be rendered

Warning content : There is a chart instance already initialized on the dom.

      //   const dom = this.$refs.echartBox
      const dom = document.querySelector('.chartBox')

Solution :

The way 1:this.$refs

Like the code at the beginning

The way 2: Pass in a unique className or id, Used to distinguish

<div class="chartBox" :id="eID"></div>

  props: {
    eID: {
      type: String,
      default: ''
    }
  },

  const dom = document.querySelector('#' + this.eID)
原网站

版权声明
本文为[Bug pill]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207061024412332.html