定义方法
/**
* echarts tooltip 自动轮播
* @param myChart //初始化echarts的实例
* @param num //类目数量(原因:循环时达到最大值后,使其从头开始循环)
* @param time //轮播间隔时长
* @param position //tooltip 位置
*/
export function autoHover(myChart, num, time, position = null) {
let defaultData = {
// 设置默认值
time: 2000,
num: 0
},
count = 0,
timeTicket = null
function initTimer() {
timeTicket && clearInterval(timeTicket)
timeTicket = setInterval(function () {
myChart.dispatchAction({
type: 'downplay',
seriesIndex: 0, // serieIndex的索引值 可以触发多个
dataIndex: count
})
count = count % num // 增加
// console.log(count, 'dataIndex')
myChart.dispatchAction({
type: 'highlight',
seriesIndex: 0,
dataIndex: count
})
myChart.dispatchAction({
type: 'showTip',
seriesIndex: 0,
dataIndex: count,
position
})
count++
if (count >= num) {
count = 0
}
}, time)
}
if (!time) {
time = defaultData.time
}
if (!num) {
num = defaultData.num
}
initTimer()
myChart.on('mouseover', function (params) {
clearInterval(timeTicket)
myChart.dispatchAction({
type: 'downplay',
seriesIndex: 0
})
myChart.dispatchAction({
type: 'highlight',
seriesIndex: 0,
dataIndex: params.dataIndex
})
myChart.dispatchAction({
type: 'showTip',
seriesIndex: 0,
dataIndex: params.dataIndex
})
})
myChart.on('mouseout', function () {
initTimer()
})
return timeTicket
}
export default {
autoHover
}
在main.js里注册
import tooltipTools from './utils/tooltip'
Vue.prototype.$tooltipTools = tooltipTools
在vueu页面调用
// 绘制表格
initCharts() {
var barOption = {
//提示框组件
tooltip: {
trigger: 'axis',
backgroundColor: 'rgba(0, 58, 31, 0.8)',
padding: 10,
borderColor: 'rgba(123, 249, 190, 0.6)',
borderWidth: 1,
textStyle: {
color: '#FBF38F',
fontSize: 14
},
/鼠标悬浮到图上,可以出现标线和刻度文本
axisPointer: {
type: 'line',
animation: false,
lineStyle: {
type: 'dashed',
color: 'rgba(164, 218, 191, .3)'
}
}
}
....
}
this.myChart = this.$echarts.init(document.getElementById('standard-top-chart'), null, {
devicePixelRatio: window.scaleScreen * 2
})
this.myChart.setOption(this.barOption)
// 在echarts渲染dom之后调用定时器
this.chartTimerTicket = this.$tooltipTools.autoHover(this.myChart, this.barOption.series[0].data.length, 2000)
}
// 记得销毁定时器
beforeDestroy() {
try {
clearInterval(this.chartTimerTicket)
} catch (err) {
console.log(err, '清除autoHover定时器失败')
}
}