vue2使用echarts报“Initialize failed: invalid dom”

201 阅读1分钟

简单记录: 关于echarts遇到的一个错误,进行一个简单的记录,方便后续的学习查询(摘要凑字..)

<template>
  <div class="echart-container">
    <div style="flex: 1" ref="container"></div>
  </div>
</template>

<script>
const option = {
  xAxis: {
    type: "category",
    data: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
  },
  yAxis: {
    type: "value",
  },
  series: [
    {
      data: [150, 230, 224, 218, 135, 147, 260],
      type: "line",
    },
  ],
};
export default {
  data() {
    return {
      option,
      chart: null,
    };
  },
  methods: {
    initChart() {
      if (this.chart) {
        this.chart.dispose();
      }
      //解决方法:判断dom是否已经生成
      if (this.$refs.container) {
        this.chart = this.$echarts.init(this.$refs.container);
        this.chart.setOption(this.option);
      }
    },
  },
  mounted() {
    this.initChart();
  },
};
</script>

<style lang="less" scoped>
.echart-container {
  width: auto;
  height: 700px;
  display: flex;
  justify-content: center;
}
</style>