解决echarts图表在项目中打包后切换页面后不显示的问题(vue3)

在工作中发现一个问题,在项目本地运行环境中echarts图表都显示正常,而打包之后的文件在首次进入页面时正常,切换页面切回便显示空白了,通过上网查询解决方案总结出两种方法

代码示例:

main.js全局挂载

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import {store, key} from './store'

import * as echarts from 'echarts' // 引入echarts

const app = createApp(App)

app.config.globalProperties.$echarts = echarts // 全局挂载echarts

app.use(store, key).use(router).mount('#app')

组件中使用

<template>
  <div>
    <div id="canvas" ref="canvas"></div>
  </div>
</template>

<script setup>
import { ref, getCurrentInstance, onMounted } from 'vue';

const { proxy } = getCurrentInstance()

const canvas = ref() // dom实例
let myChart = null // echarts实例

onMounted(() => {
  renderChart()
})

const renderChart = () => {
  myChart = proxy.$echarts.init(canvas.value)

  myChart.setOption({
    title: {
      text: 'ECharts 入门示例'
    },
    tooltip: {},
    legend: {
      data: ['销量']
    },
    xAxis: {
      data: ['衬衫', '羊毛衫', '雪纺衫', '裤子', '高跟鞋', '袜子']
    },
    yAxis: {},
    series: [
      {
        name: '销量',
        type: 'bar',
        data: [5, 20, 36, 10, 10, 20]
      }
    ]
  });
}
</script>

<style lang='less' scoped>
#canvas {
  width: 300px;
  height: 300px;
}
</style>

解决方法:

方法一、在离开页面时手动清除dom的_echarts_instance_属性

onUnmounted(() => {
  canvas.value.removeAttribute('_echarts_instance_')
})

 方法二、在离开页面时使用官方API销毁echarts实例

 

onUnmounted(() => {
  proxy.$echarts.dispose(myChart)
})

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值