有个小坑,特此记录
老规矩,废话少说,上代码。
1> yarn add echarts 先下载,
2> 我采用按需引入,在utils下新建一个needEcharts.ts
//needEcharts.ts
// 引入 echarts 核心模块,核心模块提供了 echarts 使用必须要的接口。
import * as echarts from 'echarts/core';
import { LineChart } from 'echarts/charts';
// 引入提示框,标题,直角坐标系,数据集,内置数据转换器组件,组件后缀都为 Component
import {
TitleComponent,
TooltipComponent,
GridComponent,
DatasetComponent,
TransformComponent,
ToolboxComponent,
LegendComponent
} from 'echarts/components';
import { LabelLayout, UniversalTransition } from 'echarts/features';
import { CanvasRenderer } from 'echarts/renderers';
// 注册必须的组件
echarts.use([
TitleComponent,
TooltipComponent,
GridComponent,
DatasetComponent,
TransformComponent,
ToolboxComponent,
LegendComponent,
LabelLayout,
UniversalTransition,
CanvasRenderer,
LineChart
]);
// 导出
export default echarts
3>组件中引入
import echarts from '@/utils/needEcharts'
const myChart = ref<any>(null)
const init = () => {
myChart.value = echarts.init(EchartsMain.value)
const option = {
// ...配置项
}
myChart.value.setOption(option)
};
4>屏幕大小变化动态修改canvas大小(优化)
// 防抖
const debounce = (fun: any, delay: number) => {
let timerId: any
return function () {
clearTimeout(timerId)
timerId = setTimeout(fun, delay)
}
}
const monitorSize = debounce(() => {
nextTick(() => {
myChart.value.resize()
})
}, 500)
onMounted(() => {
window.addEventListener('resize', monitorSize)
})
然后屏幕大小变化的时候会…
Cannot read properties of undefined (reading ‘type’)
TypeError: Cannot read properties of undefined (reading ‘type’)
不卖关子了,看解决办法
//markRaw 将一个对象标记为非响应式
import { markRaw } from 'vue'
const init = () => {
myChart.value = markRaw(echarts.init(EchartsMain.value))
const option = {
// ...配置项
}
myChart.value.setOption(option)
};
最后 别忘了移除。
onUnmounted(() => {
window.removeEventListener('resize', monitorSize)
})
大功告成,打完收工。如果有帮助到您,记得点赞关注哦。只分享干货。