问题一:
ERROR
Cannot read properties of undefined (reading 'init') TypeError: Cannot read properties of undefined (reading 'init')
错误原因:echarts引入方式不对
查看我的package.json文件,echarts版本是5
解决方案:在组件中将echarts4的引入方式import echarts from 'echarts'改为echarts5的引入方式
import * as echarts from 'echarts'
问题二:
ERROR
Initialize failed: invalid dom.
错误原因:无效的dom。是代码中还未加载出dom,就已经开始了echarts的初始化
<script lang="ts" setup>
// echarts5的引用方式
import * as echarts from 'echarts'
const myChart = echarts.init(document.getElementById("main"))
let option = {
xAxis: {
type: 'category',
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
},
yAxis: {
type: 'value'
},
series: [
{
data: [120, 200, 150, 80, 70, 110, 130],
type: 'bar',
showBackground: true,
backgroundStyle: {
color: 'rgba(180, 180, 180, 0.2)'
}
}
]
};
myChart.setOption(option)
</script>
解决方案:将echarts的运用放入onMounted()中,或者将echarts的运用放入定时计时器中,延时加载
<script lang="ts" setup>
import { onMounted } from 'vue'
// echarts5的引用方式
import * as echarts from 'echarts'
onMounted( ()=>{
const myChart = echarts.init(document.getElementById("main"))
let option = {
xAxis: {
type: 'category',
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
},
yAxis: {
type: 'value'
},
series: [
{
data: [120, 200, 150, 80, 70, 110, 130],
type: 'bar',
showBackground: true,
backgroundStyle: {
color: 'rgba(180, 180, 180, 0.2)'
}
}
]
};
myChart.setOption(option)
})
</script>