Table of Contents
echarts(v5.x) 在移动端使用的时候存在 tooltip 不会自动消失的问题。比如,先点击弹出 tooltip,然后点击其他组件,这时 tooltip 不会消失,容易与其他组件的弹窗重叠,并且 toolip 的层级还特别高。

这种体验就很不好。为了解决这个问题,在 github 上搜索了一下,发现已经有人提出了较好的解决方案——通过 echartsInstance.dispatchAction 取消弹窗。
mixin
为了能够让所有需要的页面方便使用,我将相关方法写成了 mixin:
// mixins/chartMixin
export default {
mounted() {
this.initListener()
},
beforeDestroy() {
this.destroyListener()
},
methods: {
initListener() {
document.addEventListener('click', this.handleTouch)
document.addEventListener('touch', this.handleTouch)
},
destroyListener() {
document.removeEventListener('click', this.handleTouch)
document.removeEventListener('touch', this.handleTouch)
},
handleTouch(e) {
// 点击非 echarts 区域,需要取消 tooltip
if (this.chartRef?.length && !e.path.find(item => item.className?.includes('echarts'))) {
this.chartRef.map(key => {
const chartInstances = []
if (Array.isArray(this.$refs[key])) {
this.$refs[key].map(ref => {
chartInstances.push(ref)
})
} else {
chartInstances.push(this.$refs[key])
}
chartInstances.map(ref => {
if (typeof ref.dispatchAction === 'function') {
ref.dispatchAction({
type: 'hideTip'
})
}
})
})
}
}
}
}
使用
然后,在需要的页面引入,并标注 echarts 的引用。
<template>
<div class="wrapper">
<!-- 用的 vue-echarts -->
<v-chart ref="chart" :option="roseOption" :autoresize="true" />
</div>
</template>
<script>
import chartMixin from '@/mixins/chart'
export default {
name: 'OperateSupervise',
mixins: [chartMixin],
data() {
return {
chartRef: ['chart'], // 标注
}
}
}
</script>
如此一来,在点击非 echarts 区域的时候,已经显示的 tooltip 就可以“自动”消失了。