echarts 圆环默认高亮,点击切换
在实现过程中主要遇到了一下难点
(1)labelLine的颜色需要和图形颜色对应
(2)扇形标签的文字样式定义(label)
- 设计图如下
- vue文件代码如下
<template>
<div :id="id" :class="className" :style="{width,height}"></div>
</template>
<script>
import resize from './mixins/resize'
//引入基本模板
let echarts = require('echarts/lib/echarts');
require('echarts/theme/macarons');//引入主题
require('echarts/lib/chart/pie')
const color = ['#3a91fd', '#ffc100', '#20dad3', '#7480f5', '#2759ff']
export default {
name: "vs-pie",
mixins: [resize],
props: {
id: {
type: String,
default: 'chart'
},
className: {
type: String,
default: 'chart'
},
width: {
type: String,
default: '100%'
},
height: {
type: String,
default: '200px'
},
seriesData: Array
},
data() {
return {
chart: null,
//默认高亮的数据项
defaultIndex: 0,
}
},
watch: {
seriesData: {
handler(val) {
const data = this.setSeries(val)
this.setOption(data)
//设置默认的选中值
this.setSelect(this.defaultIndex)
},
}
},
mounted() {
this.initChart()
},
methods: {
initChart() {
this.chart = echarts.init(document.getElementById(this.id))
this.bindClick(this.chart)
},
setOption(data) {
this.chart.setOption({
series: {
name: '访问来源',
type: 'pie',
selectedMode: 'single',
selectedOffset: 5,
radius: ['34%', '60%'],
showAbove: true,
label: {
normal: {
show: false,
fontSize: 12,
position: 'outer', //让labelLine末端对齐
alignTo: 'labelLine', //
distanceToLabelLine: 0,
padding: [-20, 0, 0, 0],
formatter: params => {
return `{pre|${params.percent.toFixed(0) + '%'}}\n{name| ${params.name}}\n`
},
rich: {
pre: {
color: '#070C12',
fontFamily: 'PingFang-SC-Bold',
align: 'left',
},
name: {
color: '#515669',
fontSize: 10,
padding: [5, 0, 5, -4],
align: 'left',
}
}
},
emphasis: {
show: true,
},
},
labelLayout: (params) => {
let isLeft = params.labelRect.x < this.chart.getWidth() / 2;
// points:labelLine的三个点坐标,改变第三个点的x坐标,增加length2的长度,达到label在labelLine线上
let points = params.labelLinePoints;
if (isLeft) { //左边
points[2][0] = params.labelRect.x
} else {
points[2][0] = params.labelRect.x + params.labelRect.width
}
return {
labelLinePoints: points
};
},
data
}
})
},
setSelect(index) {
this.chart.dispatchAction({
type: 'select',
dataIndex: index
})
this.chart.dispatchAction({
type: 'highlight',
dataIndex: index
})
},
cancelSelect(index) {
this.chart.dispatchAction({
type: 'unselect',
dataIndex: index
})
this.chart.dispatchAction({
type: 'downplay',
dataIndex: index
})
},
bindClick(chart) {
chart.on('click', (e) => {
e.dataIndex
if (e.dataIndex !== this.defaultIndex) {
this.cancelSelect(this.defaultIndex)
this.setSelect(e.dataIndex)
this.defaultIndex = e.dataIndex
}
})
},
setSeries(data) {
return data.map((item, i) => {
item.emphasis = {
labelLine: {
lineStyle: {
color: color[i]
}
}
}
item.itemStyle = {
color:color[i]
}
return item
})
}
}
}
</script>
<style scoped>
</style>