1. 程式人生 > 其它 >Vue eCharts Cannot read property ‘init‘ of undefined 報錯問題

Vue eCharts Cannot read property ‘init‘ of undefined 報錯問題

技術標籤:Vuevuetsecharts

在這裡插入圖片描述
在vue 專案中使用 eCharts ,但是專案一直報 init of undefined ,查閱很多資料,方法不一

1,元素沒有設長寬

<template>
  <div class="container">
    <div id="myChart" ref="myChart" style="width: 600px; height: 400px"></div>
  </div>
</template>

2,初始化例項應該寫在 mounted

  mounted() {
  let myCharts =  this.$echarts.init(this.$refs.myChart); ;

    let options = {
      title: {
        text: "未來一週氣溫變化", //圖表頂部的標題
        subtext: "純屬虛構", //副標題
      },
      tooltip: {
        //滑鼠懸浮框的提示文字
        trigger: "axis",
      }
, legend: { data: ["最高氣溫", "最低氣溫"], }, xAxis: [ { //x軸座標資料 type: "category", boundaryGap: false, data: ["週一", "週二", "週三", "週四", "週五", "週六"
, "週日"], }, ], yAxis: [ { //y軸座標資料 type: "value", axisLabel: { formatter: "{value} °C", }, }, ], series: [ //驅動圖表生成的資料內容陣列,幾條折現,陣列中就會有幾個對應物件,來表示對應的折線 { name: "最高氣溫", type: "line", //pie->餅狀圖 line->折線圖 bar->柱狀圖 data: [11, 11, 15, 13, 12, 13, 10], }, { name: "最低氣溫", type: "line", //pie->餅狀圖 line->折線圖 bar->柱狀圖 data: [1, -2, 2, 5, 3, 2, 0], }, ], }; myCharts.setOption(options); }

3,mounted最好加上 $nextTick

  init() {
    console.log(this.$echarts);
    console.log((document.getElementById('myChart')));
    let myCharts =  this.$echarts.init(this.$refs.myChart); ;

    let options = {
      title: {
        text: "未來一週氣溫變化", //圖表頂部的標題
        subtext: "純屬虛構", //副標題
      },
      tooltip: {
        //滑鼠懸浮框的提示文字
        trigger: "axis",
      },
      legend: {
        data: ["最高氣溫", "最低氣溫"],
      },
      xAxis: [
        {
          //x軸座標資料
          type: "category",
          boundaryGap: false,
          data: ["週一", "週二", "週三", "週四", "週五", "週六", "週日"],
        },
      ],
      yAxis: [
        {
          //y軸座標資料
          type: "value",
          axisLabel: {
            formatter: "{value} °C",
          },
        },
      ],
      series: [
        //驅動圖表生成的資料內容陣列,幾條折現,陣列中就會有幾個對應物件,來表示對應的折線
        {
          name: "最高氣溫",
          type: "line", //pie->餅狀圖  line->折線圖  bar->柱狀圖
          data: [11, 11, 15, 13, 12, 13, 10],
        },
        {
          name: "最低氣溫",
          type: "line", //pie->餅狀圖  line->折線圖  bar->柱狀圖
          data: [1, -2, 2, 5, 3, 2, 0],
        },
      ],
    };
    myCharts.setOption(options);
  }
  mounted() {
    this.$nextTick(() => {
      this.init();
    });

  }

4,以上方法都不行的話檢查一下 eCharts 的版本

"echarts": "^5.0", // 替換為4.8.0