1. 将自动轮播的工具函数封装到 utils/echart-tooltip-carousel.js
/**
* echarts自动轮播tooltip
* @param {Object} chart echart实例
* @param {Number} num 轮播数量
* @param {Number} time 轮播间隔时间
*/
export function loopShowTooltip(chart, num=20, time=2000) {
let count = 0
// 将定时器挂到echart实例上
chart.timer && clearInterval(chart.timer)
chart.timer = setInterval(function () {
chart.dispatchAction({
type: 'downplay',
seriesIndex: 0
})
chart.dispatchAction({
type: 'highlight',
seriesIndex: 0,
dataIndex: count
})
chart.dispatchAction({
type: 'showTip',
seriesIndex: 0,
dataIndex: count
})
count++
if (count >= num) {
count = 0
}
}, time)
chart.on('mouseover', function (params) {
clearInterval(chart.timer)
chart.dispatchAction({
type: 'downplay',
seriesIndex: 0
})
chart.dispatchAction({
type: 'highlight',
seriesIndex: 0,
dataIndex: params.dataIndex
})
chart.dispatchAction({
type: 'showTip',
seriesIndex: 0,
dataIndex: params.dataIndex
})
})
chart.on('mouseout', function () {
chart.timer && clearInterval(chart.timer)
chart.timer = setInterval(function () {
chart.dispatchAction({
type: 'downplay',
seriesIndex: 0
})
chart.dispatchAction({
type: 'highlight',
seriesIndex: 0,
dataIndex: count
})
chart.dispatchAction({
type: 'showTip',
seriesIndex: 0,
dataIndex: count
})
count++
if (count >= num) {
count = 0
}
}, time)
})
}
export default {
loopShowTooltip
}
2.在vue3中使用的示例
<template>
<div ref="testRef"></div>
</template>
<script>
// 通过 getCurrentInstance 访问内部组件实例
import { getCurrentInstance } from 'vue'
import { loopShowTooltip } from '@/utils/echart-tooltip-carousel.js'
export default {
data() {
// echarts实例
this.echarts = null
// 图表实例
this.chart = null
return {
}
},
mounted() {
this.drawChart()
},
methods: {
/**
* 绘制图表
*/
async drawChart() {
if (!this.echarts) {
this.echarts = getCurrentInstance().appContext.config.globalProperties.$echarts
}
const option = {...}
// 获取数据
....
if (!this.chart) {
this.chart = this.echarts.init(this.$refs.testRef)
}
this.chart.setOption(option)
// 自动轮播
loopShowTooltip(this.chart, 12, 2000)
}
}
}
</script>
3.效果