开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第25天,点击查看活动详情
写在前面
上篇文章介绍了在vite+vue的后台项目中实现双折线图的线性渐变,本篇文章介绍如何在vite+vue项目中画一个简单的柱状图
完整源码:项目gitee地址
在线演示:演示地址
账号:admin
密码:admin
画一个简单的柱状图
带背景色
showBackground: true,
backgroundStyle: {
color: 'rgba(180, 180, 180, 0.2)'
}
单个柱子改变颜色
data: [
120,
{
value: 200,
itemStyle: {
color: '#a90000'
}
},
150,
80,
70,
110,
130
],
柱子渐变
0, 0, 0, 1 表示从上到下渐变,改成 0, 0, 1, 0 就成了从左到右渐变,改成其他值([0,1]之间)还可以变成各种角度的渐变
itemStyle: {
color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
{ offset: 0, color: '#83bff6' },
{ offset: 0.5, color: '#188df0' },
{ offset: 1, color: '#188df0' }
])
},
柱子上方显示值
label: {
show: true,
position: 'top'
},
添加图例
legend: {
data: ['销售量']
},
下面是一个简单例子,创建一个名为main2的ref容器,定义echarts:echarts.init(main2.value),绘制图表:myChart.setOption(option),option即为我们所绘制图表的配置项,通过更改配置项内容改变图表。绘制图表的方法须在vue的onMounted生命周期钩子函数中执行,否则页面还没有渲染完成,此时main2是不存在的。
<template>
<div ref="main2" class="main2"></div>
</template>
<script setup lang="ts">
import * as echarts from 'echarts';
import { onMounted, ref } from 'vue';
onMounted(() => {
initChart2()
})
const main2 = ref()
const initChart2 = () => {
let myChart = echarts.init(main2.value);
let option = {
legend: {
data: ['销售量'],
textStyle: {
color: '#fff'
}
},
xAxis: {
type: 'category',
data: ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期七']
},
yAxis: {
type: 'value'
},
series: [
{
name: '销售量',
data: [
120,
{
value: 200,
itemStyle: {
color: '#a90000'
}
},
150,
80,
70,
110,
130
],
type: 'bar',
showBackground: true,
backgroundStyle: {
color: 'rgba(180, 180, 180, 0.2)'
},
itemStyle: {
color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
{ offset: 0, color: '#83bff6' },
{ offset: 0.5, color: '#188df0' },
{ offset: 1, color: '#188df0' }
])
},
label: {
show: true,
position: 'top'
},
}
]
}
myChart.setOption(option);
}
</script>
<style lang="less" scoped>
.main2 {
width: 500px;
height: 300px;
margin: 10px;
background-color: #102A49;
}
</style>
最终效果如下:
写在最后
以上就是在vite+vue项目中画一个简单的柱状图的所有代码和说明