柱状图
<template>
<div class="ringRadio" ref="chart">
</div>
</template>
<script>
// 柱状图
import * as echarts from 'echarts'
//object深替换
const deepAssign = (obj, obj1) => {
for (let key in obj1) {
if (typeof obj1[key] == 'object') {
if (!obj[key]) obj[key] = obj1[key] instanceof Array ? [] : {};
deepAssign(obj[key], obj1[key]);
} else {
obj[key] = obj1[key];
}
}
}
export default {
props: {
barData: Array,
option: Object,
},
data() {
return {
barDatas: [],
chartObj: {
text: '',// 标题
// nomalColor: 'red', // 占比的色环
startAngle: '-270' // 开始的角度
},
options: {}, // echarts的配置
size: 20, // 字体大小
chart: null, // echarts实例
}
},
watch: {
barData(val) {
if (val.length) {
this.$refs.chart.style.display = 'block';
let option = {
series: [
{
data: val
}
]
}
deepAssign(this.options, option);
this.initChart()
} else {
this.$refs.chart.style.display = 'none';
}
},
option(val) {
deepAssign(this.options, val);
this.initChart()
}
},
created() {
console.log(this.option)
this.initDate()
window.addEventListener('resize', this.initChart)
},
mounted() {
if (this.timer) clearTimeout(this.timer)
// 确保dom渲染
this.timer = setTimeout(() => {
this.initChart()
}, 20)
},
methods: {
// 根据数据初始化配置
initDate() {
this.chartObj.text = this.percent
// 字体大小自适应变化
let len = (this.percent + '').length
if (len >= 2) {
this.size -= (len - 2) * 4
this.size < 10 && (this.size = 10)
this.left += (len - 2) * 7
}
if (this.percent < 0) {
this.chartObj.nomalColor = '#000'
let ret = (Math.abs(this.percent) - 25) * 360 / 100
this.chartObj.startAngle = ret
}
},
// 设置echarts配置
setData() {
if (!this.option.xAxis) return;
this.options = {
color: ['#ff6200'],
grid: {
left: '5%',
right: '2%',
containLabel: true
},
xAxis: [
{
type: 'category',
data: this.option.xAxis[0].data,
// show: false,
axisLabel: {
show: true,
interval: 0,
textStyle: {
color: 'rgba(0,0,0,.3)',//坐标值得具体的颜色
}
},
axisLine: {
lineStyle: {
fontSize: '10px',
width: '0'
}
},
axisTick: { //去掉刻度线
show: false
}
}
],
yAxis: [
{
type: 'value',
axisLabel: {
show: true,
interval: 0,
textStyle: {
color: 'rgba(0,0,0,.3)',//坐标值得具体的颜色
}
},
axisLine: {
show: false,
lineStyle: {
type: 'dashed',
width: '0'
}
},
splitLine: {
lineStyle: {
type: 'dashed',
color: 'rgba(0,0,0,.03)'
}
},
axisTick: {
show: false
}
}
],
series: [
{
type: 'bar',
barWidth: '20px',
data: this.barDatas,
label: {
fontSize: 8,
color: 'rgba(0,0,0,.1)',
normal: {
show: true,
color: 'rgba(0,0,0,.7)',
position: 'top'
}
},
}
]
};
deepAssign(this.options, this.option)
},
// 初始化chart
initChart() {
this.setData()
let chart
// 做判断保证对象单一
if (this.chart) {
chart = this.chart
} else {
chart = echarts.init(this.$refs.chart)
this.chart = chart
}
chart.setOption(this.options)
// 父容器变化时重新计算,保证自适应
this.chart.resize();
},
},
destroyed() {
clearTimeout(this.timer)
window.removeEventListener('resize', this.initChart)
}
}
</script>
<style lang="less" scoped>
/* 宽高设置成100%,保证和父盒子的高度一致*/
.ringRadio {
width: 100%;
height: 100%;
}
</style>
浙公网安备 33010602011771号