在工作中发现一个问题,在项目本地运行环境中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)
})