首先,进入页面初始化echarts图表
注意,初始化图表的同时应添加页面的监听事件,防止在页面缩放时图标未能重绘而导致样式错乱
// 初始化ehcarts图
echartsInit() {
this.$nextTick(() => {
// 重绘echarts
window.addEventListener('resize', () => {
const elementIds = [
'echarts-all',
'echarts-danger',
'echarts-region',
'echarts-status',
'echarts-trend'
]
elementIds.map((item) => {
const chartDom = document.getElementById(item)
const chartTrend = chartDom && echarts.init(chartDom)
chartTrend && chartTrend.resize()
})
})
})
},
echarts绘制饼图示例
// 渲染echarts
render_echartsPie(data, id) {
var chartDom = document.getElementById(id)
var myChart = chartDom && echarts.init(chartDom)
var option
// 人车企概览环饼图配置参数
option = {
color: [
'#22c4ff',
'#1ee7d4',
'#ffb743',
'#ff7943',
'#ffe0ab',
'#6bc5f4',
'#c08ef2',
'#ffda49'
],
tooltip: {
trigger: 'item'
},
legend: {
orient: 'vertical',
top: 'center',
right: '0%',
icon: 'rect',
itemWidth: 10,
itemHeight: 10,
textStyle: {
color: '#fff'
},
formatter: function(name) {
var data = option.series[0].data
var total = 0
var tarValue
for (var i = 0; i < data.length; i++) {
total += data[i].value
if (data[i].name === name) {
tarValue = data[i].value
}
}
var p = ((tarValue / total) * 100).toFixed(2)
return `${name} ${p}%`
}
},
series: [
{
name: '',
type: 'pie',
radius: ['45%', '70%'],
// 饼图位置参数
center: [id === 'echarts-region' || id === 'echarts-status' ? '45%' : '30%', '50%'],
avoidLabelOverlap: false,
itemStyle: {
// 设置不生效
borderRadius: 10,
borderWidth: 5
},
label: {
show: false,
position: 'center',
formatter: '{b_style|{b}}\n{c_style|{c}}\n{b_style|{d}%}',
rich: {
b_style: {
fontSize: 12
},
c_style: {
color: '#fff',
fontSize: 18,
padding: [5, 0, 5, 0]
}
}
},
emphasis: {
label: {
show: true,
fontSize: '14',
fontWeight: 'normal'
}
},
labelLine: {
show: false
},
data: data
}
]
}
myChart && myChart.setOption(option)
this.handleChartLoop(option, myChart)
},
echarts饼图轮播方法处理
- 饼图自动轮播
- 鼠标覆盖饼图时停止自动轮播并高亮当前项,鼠标移出时继续从当前项重新开始轮播
// 饼图自动轮播
handleChartLoop(option, myChart) {
if (!myChart) {
return
}
let currentIndex = -1 // 当前高亮图形在饼图数据中的下标
let changePieInterval = setInterval(selectPie, 1000) // 设置自动切换高亮图形的定时器
// 取消所有高亮并高亮当前图形
function highlightPie() {
// 遍历饼图数据,取消所有图形的高亮效果
for (var idx in option.series[0].data) {
myChart.dispatchAction({
type: 'downplay',
seriesIndex: 0,
dataIndex: idx
})
}
// 高亮当前图形
myChart.dispatchAction({
type: 'highlight',
seriesIndex: 0,
dataIndex: currentIndex
})
}
// 用户鼠标悬浮到某一图形时,停止自动切换并高亮鼠标悬浮的图形
myChart.on('mouseover', (params) => {
clearInterval(changePieInterval)
currentIndex = params.dataIndex
highlightPie()
})
// 用户鼠标移出时,重新开始自动切换
myChart.on('mouseout', (params) => {
if (changePieInterval) {
clearInterval(changePieInterval)
}
changePieInterval = setInterval(selectPie, 1000)
})
// 高亮效果切换到下一个图形
function selectPie() {
var dataLen = option.series[0].data.length
currentIndex = (currentIndex + 1) % dataLen
highlightPie()
}
},