您的位置:首页 > Web前端 > Vue.js

uniapp在Vue页面中使用echarts绘制堆叠柱状图

2020-06-05 16:50 323 查看

想要在uniapp中使用echarts,需要进行以下操作步骤:
一:操作步骤
1.定义存放图表的div;
2.引入echarts.min,js,可以去echarts的官网“在线定制”;
3.在需要使用echarts的图表vue页面引入echarts.min.js;
4.开始使用echarts绘制图表,此案例是动态的给图表赋值。

具体代码如下:
定制js:

test.vue页面

<style scoped>
h2{
text-align: center;
padding: 30px;
font-size: 18px;
}
#chart_example{
width: 100%;
height: 500px;
border: 1px solid red;
margin: 0 auto;
}
</style>
<template>
<div>
<h2>vue中插入Echarts示例</h2>
<div id="chart_example">

</div>
</div>
</template>

<script>
import echarts from '@/js/echarts.min.js'
export default {
data() {
return {}
},
mounted() {
this.inc();
this.ectest(this.dataparam,this.normal,this.ask,this.late,this.early);

},
methods: {
ectest(dataparam,normal,ask,late,early){
let this_ = this;
//初始化图表
let myChart = echarts.init(document.getElementById('chart_example'));
//构建图表
let option = {
tooltip: {
trigger: 'axis',
axisPointer: {            // 坐标轴指示器,坐标轴触发有效
type: 'shadow'        // 默认为直线,可选为:'line' | 'shadow'
}
},
legend: {
data: ['正常', '请假', '迟到', '早退']
},
grid: {
left: '3%',
right: '4%',
bottom: '3%',
containLabel: true
},
xAxis: {
type: 'value'
},
yAxis: {
type: 'category',
data: dataparam
},
series: [
{
name: '正常',
type: 'bar',
stack: '总量',
label: {
show: true,
position: 'insideRight'
},
data: normal
},
{
name: '请假',
type: 'bar',
stack: '总量',
label: {
show: true,
position: 'insideRight'
},
data: ask
},
{
name: '迟到',
type: 'bar',
stack: '总量',
label: {
show: true,
position: 'insideRight'
},
data: late
},
{
name: '早退',
type: 'bar',
stack: '总量',
label: {
show: true,
position: 'insideRight'
},
data: early
}
]
};
myChart.setOption(option);

//建议加上以下这一行代码,不加的效果图如下(当浏览器窗口缩小的时候)。超过了div的界限(红色边框)
window.addEventListener('resize',function() {myChart.resize()});
},
//调用接口给图表动态赋值
inc(){
uni.request({
url:'数据接口',
data:{
classid:1,
begintimes:'2020-02-02',
endtimes:'2020-02-02',
classnames:'yuwen'
},
method:'GET'
}).then(res=>{
console.log(res[1].data)
var arr=[];
var normal=[];
var ask=[];
var late=[];
var early=[];
var len=res[1].data.series;
if(res[1].data.code==0){
for(var i=0;i<len.length;i++){
arr.push(len[i].name);
normal.push(len[i].normal);
ask.push(len[i].ask);
late.push(len[i].late);
early.push(len[i].early);
}
console.log(arr)
console.log(normal)
console.log(ask)
console.log(late)
console.log(early)
this.ectest(arr,normal,ask,late,early)

}
})
}
},
watch: {},
created() {

}
}
</script>

二:关于动态绘制图表调用接口的步骤
*方法一:*如上案例
1.把初始化图表和创建图表放在一个方法中ectest(dataparam,normal,ask,late,early),这个方法中的参数是要动态赋给图表的值;
2.再定义一个方法inc(),去调用后台返回数据的接口,然后在接口的回调中调用创建图表的方法ectest(dataparam,normal,ask,late,early),并给这些参数赋值,把图表中需要动态获取值的部分用以上参数替换。
方法二:

三:补充
uni.request({}).then(res=>{}),.then是回调接口返回的数据,并把数据赋值给图表

此案例是针对echarts的堆叠柱形图,其他的图表同样适用!!!

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: