vue3之echarts渐变柱状图
效果:
核心代码:
<template>
<div class="abnormal">
<div class="chart" ref="chartsRef"></div>
</div>
</template>
<script setup>
import * as echarts from 'echarts';
import { reactive, onMounted } from 'vue';
const obj = reactive({
data: {
xdata: [
'1',
'2',
'3',
'4',
'5',
'6',
'7',
'8',
'9',
'10',
'11',
'12',
],
ydata: [350, 320, 310, 450, 150, 300, 250, 250, 310, 280, 200, 180],
},
op: {
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'shadow',
lineStyle: {
color: 'rgba(135, 140, 147, 0.6)',
width: 10,
},
}, // 鼠标移上的阴影,默认是线
},
grid: {
top: '5%',
right: '1%',
left: '0%',
bottom: '0%',
containLabel: true,
},
xAxis: [],
yAxis: [
{
type: 'value',
name: '装载量(万吨)',
position: 'left',
axisLabel: {
formatter: '{value}',
color: '#FFFFFF',
textStyle: {
fontSize: 13,
fontFamily: 'DINPro-Regular',
},
interval: 0,
},
axisLine: {
show: false,
lineStyle: {
color: 'rgba(255,255,255,1)',
},
},
axisTick: {
// x轴刻度相关设置
alignWithLabel: true,
},
splitLine: {
lineStyle: {
type: 'dashed',
color: 'rgba(255,255,255,0.12)',
},
},
},
{
type: 'value',
name: '装载车次(千辆)',
nameLocation: 'end',
position: 'right',
axisTick: {
show: false,
},
axisLine: {
show: false,
},
axisLabel: {
formatter: '{value}',
textStyle: {
fontSize: 13,
color: '#ffffff',
fontFamily: 'DINPro-Regular',
},
},
axisTick: {
// x轴刻度相关设置
alignWithLabel: true,
},
splitLine: {
lineStyle: {
type: 'dashed',
color: 'rgba(160, 169, 192, 0.8)',
},
},
},
],
series: [],
}
})
let myCharts = null;
let chartsRef = ref(null)
const flushChart = () => {
obj.op.xAxis = [];
obj.op.series = [];
obj.op.xAxis.push(
{
type: 'category',
data: obj.data.xdata,
axisLine: {
lineStyle: {
color: 'rgba(255,255,255,0.12)',
},
},
axisLabel: {
margin: 11,
color: '#FFFFFF',
textStyle: {
fontSize: 13,
fontFamily: 'DINPro-Regular',
},
},
}
);
obj.op.series.push(
{
type: 'bar',
data: obj.data.ydata,
name: '装载量',
stack: 'Ad',
barWidth: '5px',
itemStyle: {
normal: {
color: new echarts.graphic.LinearGradient(
0,
0,
0,
1,
[
{
offset: 0,
color: '#77FB9F', // 0% 处的颜色
},
{
offset: 1,
color: 'rgba(255,255,255,0)', // 100% 处的颜色
},
],
false,
),
},
},
},
);
myCharts.setOption(obj.op);
}
const initChart = () => {
myCharts = echarts.init(chartsRef.value);
}
onMounted(() => {
initChart();
flushChart();
})
const destroyChart = () => {
if (!myCharts) {
return;
}
myCharts.dispose();
myCharts = null;
}
onBeforeMount(() => {
destroyChart();
})
</script>
<style lang="scss" scoped>
.abnormal {
position: relative;
width: 100%;
height: 276px;
margin-top: 19px;
display: inline-block;
.chart {
display: inline-block;
width: 100%;
height: 185px;
zoom: 1;
}
}
</style>