vue Echarts自适应浏览器resize报错:Cannot read property 'resize' of undefined

Echarts自适应浏览器resize报错:Cannot read property 'resize' of undefined

1.问题

今天在做Echarts自适应浏览器时,发现拖动窗口进行缩放时,会出现一个问题:Cannot read property ‘resize’ of undefined。

Echarts插件绘制的柱状图正常情况下页面截图:
在这里插入图片描述
但是当我拖动浏览器窗口的边框进行缩放时会报错:
在这里插入图片描述
相关代码如下:

    mounted() {
   
   
      //在mounted生命周期函数中实例化echarts对象
      this.drawHistogarm();
    },
    methods:{
   
   
      drawHistogarm(){
   
   
        //初始化echarts实例
        let histogram = this.$echarts.init(do
在进行 Echarts 柱状图 resize 操作时出现 “TypeError: Cannot read properties of undefined (reading 'type')” 错误,通常是由于 Echarts 实例受到 Vue 响应式处理的影响。以下是具体的解决办法: ### 组合式中使用 markRaw 在组合式 API 里,运用 `markRaw` 标记无需进行响应式处理的对象,防止被 `proxy` 影响。示例代码如下: ```javascript import { markRaw, onMounted, ref } from 'vue'; import * as echarts from 'echarts'; export default { setup() { const chartRef = ref(null); let chart; onMounted(() => { const el = chartRef.value; chart = markRaw(echarts.init(el)); // 避免被 proxy // 柱状图配置项 const 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' } ] }; chart.setOption(option); // 模拟 resize 操作 window.addEventListener('resize', () => { chart.resize(); }); }); return { chartRef }; } }; ``` ### 选项式中直接挂在 this 上 在选项式 API 中,不在 `data` 里 `return` Echarts 实例,而是直接将其挂载到 `this` 上。示例代码如下: ```javascript import * as echarts from 'echarts'; export default { data() { return { option: null // 只保留 option,移除 myChart }; }, methods: { initChart() { this.myChart = echarts.init(this.$refs.chartDom); // 直接挂在 this 上 // 柱状图配置项 const 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' } ] }; this.myChart.setOption(option); // 模拟 resize 操作 window.addEventListener('resize', () => { this.myChart.resize(); }); } }, mounted() { this.initChart(); } }; ```
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值