解决vue3中使用echart 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>

猜你喜欢

转载自blog.csdn.net/weixin_45150813/article/details/128182858