直接上效果
说明
为柱状图添加横向导航条(实现多项数据的滑动展示、并为X轴标签添加鼠标事件)
完整代码
<template>
<div class="content-box">
<el-button class="back-btn" icon="el-icon-back" @click="$router.push({ path: '/' })">返回首页</el-button>
<div class="echarts-box" ref="echartsBox"></div>
</div>
</template>
<script>
import * as echarts from 'echarts'
export default {
name: 'ECharts',
components: {},
data() {
return {}
},
computed: {},
mounted(){
this.chartsFun()
},
methods: {
chartsFun(){
let chartObj = echarts.init(this.$refs.echartsBox)
chartObj.setOption({
title: {
text: 'echarts 图添加出导航条',
left: 'center'
},
tooltip: {
show: true,
trigger: 'axis'
},
grid: {
top: 50,
right: 30,
left: 60
},
xAxis: {
type: 'category',
data: ['酒醴1', '酒醴2', '酒醴3', '酒醴4', '酒醴5', '酒醴6', '酒醴7', '酒醴8', '酒醴9', '酒醴10', '酒醴11', '酒醴12', '酒醴13', '酒醴14', '酒醴15', '酒醴16', '酒醴17', '酒醴18'],
triggerEvent: true // 坐标轴的标签是否响应和触发鼠标事件,默认不响应
},
yAxis: {
type: 'value'
},
dataZoom: [
{ // 导航部分的样式控制
type: 'slider',
show: true, // 可根据判断显隐
zoomLock: true,
height: 15,
right: 30,
bottom: 15,
left: 55,
showDetail: false,
handleSize: 0,
fillerColor: '#999',
borderColor: '#666',
startValue: 0, // 一页显示条数的起始值(从0开始)
endValue: 9, // 一页显示条数的结束值(0-9共10条)
minValueSpan: 0, // 一页显示条数的最小值
maxValueSpan: 9 // 一页显示条数的最大值
},
{ // 没有这部分的话,只能拖动滚动条,鼠标滚轮不能控制外部滚动条
type: 'inside',
zoomOnMouseWheel: false,
moveOnMouseMove: true,
moveOnMouseWheel: true
}
],
series: [
{
type: 'bar',
barWidth: '75%',
barMaxWidth: 100,
data: [112, 89, 54, 172, 99, 100, 200, 350, 18, 22, 410, 80, 510, 650, 66, 880, 320, 2500]
}
]
})
window.addEventListener('resize', () => { // 跟随窗口实时变化
chartObj.resize()
})
this.navExtension(chartObj)
},
// 为坐标轴的标签添加鼠标事件
navExtension(chart){
if(!document.getElementById('cus_Div')){
let cusDiv = document.createElement('div')
cusDiv.setAttribute('id', 'cus_Div')
cusDiv.style.display = 'block'
document.querySelector('html').appendChild(cusDiv)
}
chart.on('mouseover', params => {
if(params.componentType == 'xAxis'){
let eleDiv = document.querySelector('#cus_Div')
eleDiv.style.cssText = 'position: absolute; z-index: 99999; font-size: 12px; color: #fff; padding: 5px; display: inline; border-radius: 4px; background-color: #303133; box-shadow: rgba(0, 0, 0, 0.3) 2px 2px 8px;'
eleDiv.innerHTML = params.value
document.querySelector('html').onmousemove = event => {
let x = event.pageX - 10
let y = event.pageY + 15
eleDiv.style.top = `${y}px`
eleDiv.style.left = `${x}px`
}
}
})
chart.on('mouseout', params => {
if(params.componentType == 'xAxis'){
let eleDiv = document.querySelector('#cus_Div')
eleDiv.style.display = 'none'
}
})
}
}
}
</script>
<style scoped>
.echarts-box{
width: 100%;
height: 400px;
padding-top: 50px;
}
</style>