引入echarts报错Cannot read properties of undefined (reading ‘init‘)

在引入echarts需要使用关键字as,否则引入无效

在main方法中引入

错误

import Vue from 'vue'
import App from './App.vue'
import echarts from 'echarts'

Vue.config.productionTip = false

Vue.prototype.echarts = echarts

new Vue({
  render: h => h(App)
}).$mount('#app')

正确

import Vue from 'vue'
import App from './App.vue'
import * as echarts from 'echarts'

Vue.config.productionTip = false

Vue.prototype.echarts = echarts
new Vue({
  render: h => h(App)
}).$mount('#app')

在组件中引入

错误

<template>
  <div>
    <div id="main" style="width: 600px;height:400px;"></div>
  </div>
</template>
<script>
import echarts from 'echarts'
export default {
  data(){
    return{

    }
  },
  mounted(){
    this.initEchart()
  },
  methods: {
    initEchart(){
      let myChart = echarts.init(document.getElementById('main'));
      let option = {
        title: {
          text: ''
        },
        tooltip: {},
        legend: {
          data:['']
        },
        xAxis: {
          data: ['']
        },
        yAxis: {},
        series: [{
          name: '',
          type: 'bar',
          data: [5, 20, 36, 10, 10, 20]
        }]
      }
      myChart.setOption(option);
    }
  }
}
</script>

正确

<template>
  <div>
    <div id="main" style="width: 600px;height:400px;"></div>
  </div>
</template>
<script>
import * as echarts from 'echarts'
export default {
  data(){
    return{

    }
  },
  mounted(){
    this.initEchart()
  },
  methods: {
    initEchart(){
      let myChart = echarts.init(document.getElementById('main'));
      let option = {
        title: {
          text: ''
        },
        tooltip: {},
        legend: {
          data:['']
        },
        xAxis: {
          data: ['']
        },
        yAxis: {},
        series: [{
          name: '',
          type: 'bar',
          data: [5, 20, 36, 10, 10, 20]
        }]
      }
      myChart.setOption(option);
    }
  }
}
</script>

猜你喜欢

转载自blog.csdn.net/m0_46114541/article/details/127771279