echarts组件——柱状图横向
组件代码
<template>
<div :class="classname" :style="{height:height,width:width}" />
</template>
<script>
// 横向柱状图
import * as echarts from 'echarts'
require('echarts/theme/macarons') // echarts theme
import resize from './mixins/resize'
const animationDuration = 2000
export default {
mixins: [resize],
props: {
classname: {
type: String,
default: 'chart'
},
width: {
type: String,
default: '100%'
},
height: {
type: String,
default: '100%'
},
color: { // 柱状条颜色
type: Array,
default: () => ['#58C971', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc']
},
yaxisdata: { // y轴数据
type: Array,
default: () => []
},
legenddata: { // 图例
type: String,
default: ''
},
bardata: { // 数据
type: Array,
default: () =>
[]
},
totalname: { // tooltip内容 共计的名字
type: String,
default: '数量'
},
labelshow: {
type: Boolean,
default: () => true
},
gridbottom: {
type: String,
default: '60'
}
},
data() {
return {
series: [],
chart: null
}
},
watch: {
bardata: {
deep: true,
handler(val) {
this.$nextTick(() => {
this.series = this.bardata
this.initChart()
})
}
}
},
mounted() {
},
beforeDestroy() {
if (!this.chart) {
return
}
this.chart.dispose()
this.chart = null
},
methods: {
initChart() {
this.chart = echarts.init(this.$el, 'macarons')
this.chart.setOption({
color: this.color,
tooltip: {
trigger: 'axis',
axisPointer: { // 坐标轴指示器,坐标轴触发有效
type: 'line' // 默认为直线,可选为:'line' | 'shadow'
},
formatter: (params) => {
if (params[0].value) {
let result = `<div>${params[0].axisValue}</div>`
let totalValue = 0
params.map((item, index) => {
totalValue += item.value
})
result += `<div style="display: flex; justify-content: space-between"><span>${this.totalname}: </span><span>${totalValue}</span></div>`
return result
}
}
},
legend: {
show: false,
data: [this.legenddata],
bottom: '0'
},
grid: {
top: '3%',
left: '2%',
right: '0',
bottom: this.gridbottom,
containLabel: true
},
xAxis: {
type: 'value',
boundaryGap: [0, 0.01],
axisLabel: {
show: false
},
axisLine: {
show: false
},
splitLine: {
show: false
},
splitArea: {
show: false
}
},
yAxis: {
type: 'category',
inverse: true, // 这里设置y轴倒序
axisTick: {
show: false
},
axisLine: {
show: false
},
axisLabel: {
color: 'rgba(44, 53, 66, 0.65)'
},
splitArea: {
show: false
},
data: this.yaxisdata
},
series: {
name: this.legenddata,
type: 'bar',
// barWidth: 40,
animationDuration,
data: this.series,
label: {
show: this.labelshow,
position: 'insideLeft', // 位置
align: 'left', // 数值左对齐
color: '#ffffff',
fontSize: 12,
fontWeight: '400'
// formatter: '{c}%' // 这里是数据展示的时候显示的数据
} // 柱子上方的数值
}
})
}
}
}
</script>
使用组件,传值格式可以看组件的默认数据的格式