小程序项目中有个页面,需要展示横向堆叠柱状图,到插件市场找了一圈,只看到几种charts插件,而且只有纵向堆叠柱状图和横向柱状图的demo,没看到横向堆叠柱状图的实现方案。只能自己来写了,下面是效果预览。
完整代码如下:
<template>
<view class="">
<view class="is-flex is-justify-between is-align-center has-pad">
<view class="is-flex is-justify-start is-align-center">
<view class="has-mgr-10">
a
</view>
<view :style="{backgroundColor:a}" style="width:40rpx;height:40rpx;">
</view>
</view>
<view class="is-flex is-justify-start is-align-center">
<view class="has-mgr-10">
b
</view>
<view :style="{backgroundColor:b}" style="width:40rpx;height:40rpx;">
</view>
</view>
<view class="is-flex is-justify-start is-align-center">
<view class="has-mgr-10">
c
</view>
<view :style="{backgroundColor:c}" style="width:40rpx;height:40rpx;">
</view>
</view>
<view class="is-flex is-justify-start is-align-center">
<view class="has-mgr-10">
d
</view>
<view :style="{backgroundColor:d}" style="width:40rpx;height:40rpx;">
</view>
</view>
</view>
<!-- 未找到横向堆叠柱状图的范例,故使用css自行开发 -->
<view v-if="maxNum" class="has-pad">
<view class="is-flex is-justify-between is-align-center has-mgt-10" v-for="(item,index) in dataList" :key="index">
<view class="" style="width:80rpx;">
{{item.name}}
</view>
<view class="is-flex is-justify-start is-align-center" style="width:calc(100% - 200rpx);height: 40rpx;">
<view class="" style="height: 100%;" :style="{width:100*item.a/maxNum+'%',backgroundColor:a}">
</view>
<view class="" style="height: 100%;" :style="{width:100*item.b/maxNum+'%',backgroundColor:b}">
</view>
<view class="" style="height: 100%;" :style="{width:100*item.c/maxNum+'%',backgroundColor:c}">
</view>
<view class="" style="height: 100%;" :style="{width:100*item.d/maxNum+'%',backgroundColor:d}">
</view>
</view>
<view class="" style="width:80rpx;">
{{item.total}}
</view>
</view>
</view>
</view>
</template>
<script>
let t = null;
export default {
components: {},
data() {
return {
a: '#308CFF',
b: '#09bb07',
c: '#e64340',
d: '#ffff00',
maxNum: 0,
dataList: [{
name: "A",
a: 20,
b: 10,
c: 40,
d: 30,
total: 100
}, {
name: "B",
a: 10,
b: 0,
c: 40,
d: 0,
total: 50
}, {
name: "C",
a: 20,
b: 10,
c: 10,
d: 25,
total: 65
}]
}
},
onLoad() {
t = this;
//遍历dataList,取total最大值
let maxNum = 0;
for (let i of t.dataList) {
if (i.total > maxNum) {
maxNum = i.total;
}
}
t.maxNum = maxNum;
},
methods: {
}
}
</script>
<style>
.is-align-center {
align-items: center;
}
.is-justify-start {
justify-content: flex-start;
}
.is-justify-between {
justify-content: space-between;
}
.is-flex {
display: flex;
}
.has-pad {
padding: 20rpx 30rpx !important;
}
.has-mgr-10 {
margin-right: 20rpx !important;
}
.has-mgt-10 {
margin-top: 20rpx !important;
}
</style>
核心代码是<view style="height: 100%;" :style="{width:100*item.a/maxNum+'%',backgroundColor:a}">,意思是根据当前子项的数值与最大总数的比值来绘制子项图形width。