解决vue3中使用echart报错:Cannot read properties of undefined (reading ‘type‘)
作者:不想掉头发啊!!
在Vue项目中使用Echarts进行数据可视化是非常常见的需求,然而有时候在引入Echarts的过程中可能会遇到报错,本文主要介绍了解决vue3中使用echart报错:Cannot read properties of undefined (reading ‘type‘),感兴趣的可以了解一下
一、报错原因
出现如下报错的原因是:
Proxy 应用到了整个 ECharts 实例上的问题,不太建议把整个 ECharts 实例这样的对象放到 ref 里,容易影响到实例底层的运行。可以使用 shallowRef 替代,这样 Proxy 不会应用到 ECharts 实例底下的各个属性上。

二、解决办法
把echart实例对象不要用ref等响应式保存,可以使用shallowRef等浅层作用进行保存。点击前往官网查看


具体代码:
<template>
<div ref="dom" class="charts" style="width: 100%; height: 100%;"></div>
</template>
<script setup>
import echarts from 'echarts'
import {onMounted, ref, onBeforeUnmount, watch, shallowRef} from 'vue'
import {on, off} from '@/utils/tools';
// props传值
const props = defineProps({
option: Object
})
// 元素
const dom = ref(null)
// echart实例 ---------------------------------------这里使用shallowRef进行保存[添加链接描述](https://cn.vuejs.org/api/reactivity-advanced.html#shallowref)
const chart = shallowRef(null)
// 绘制echart
const initChart = () => {
chart.value = echarts.init(dom.value)
chart.value.setOption(props.option, true)
}
// 图表变化
const chartResize = () => {
chart.value.resize()
}
watch(() => props.option, (value) => {
chart.value.clear()
chart.value.setOption(value)
})
onMounted(() => {
initChart()
on(window, 'resize', chartResize)
})
onBeforeUnmount(() => {
off(window, 'resize', chartResize)
})
</script>
<style scoped lang="less">
</style>到此这篇关于解决vue3中使用echart报错:Cannot read properties of undefined (reading ‘type‘)的文章就介绍到这了,更多相关vue3使用echart报错内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
