如何用echarts获取后台数据
如何使用echarts做到数据可视化首先我们一点要去官网,自己先做出一个没有数据交互的静态的echarts静态echarts不会的可以看我的这个博客我先给大家上效果图:这里的数据是从后台传过来的,但是这里我是自己弄的一个node的后台服务总共15条数据,接下来废话不多说,上代码:做过静态的echarts的肯定都知道,这是初始化这个图表initChart () {this.chartInstance
如何使用echarts做到数据可视化
首先我们一点要去官网,自己先做出一个没有数据交互的静态的echarts
静态echarts
不会的可以看我的这个博客
我先给大家上效果图:
这里的数据是从后台传过来的,但是这里我是自己弄的一个node的后台服务
总共15条数据,接下来废话不多说,上代码:
做过静态的echarts的肯定都知道,这是初始化这个图表
initChart () {
this.chartInstance = this.$echarts.init(this.$refs.seller_ref)
},
记得定义一个div并且设置好宽高用来放图表,这个ref就是为了更好地初始化这个图表
<template>
<div class="com-container">
<div class="com-chart" ref="seller_ref"></div>
</div>
</template>
我需要在项目加载的时候就初始化这个图表,所以我们需要在vue中的mounted内进行初始化
在我们拿数据的时候又写了第二个方法,getData,首先要在data中定义一个allData,因为后台是promise,所以我们需要更好的拿到数据,于是运用到了async和await
async getData () {
const { data: res } = await this.$http.get('seller')
console.log(res)
this.allData = res
this.updateChart()
},
this.$http就是我们在main中先封装好了,其实他就是发送一个axios的get请求,这样就减少了代码量,以及那个{data:res}就是简单的包装了一下后台发送过来的15个数据
接下来的update
updateChart () {
// 循环遍历出x轴的name
const sellerName = this.allData.map((item) => {
return item.name
})
const sellerValue = this.allData.map((item) => {
return item.value
})
const option = {
xAxis: {
type: 'value'
},
yAxis: {
type: 'category',
data: sellerName
},
tooltip: {
// 坐标轴触发
trigger: 'axis',
axisPointer: {
// 鼠标移动到柱状图上,显示为交叉线,
type: 'cross',
label: {
backgroundColor: '#6a7985'
}
}
},
series: [
{
type: 'bar',
data: sellerValue
}
]
}
this.chartInstance.setOption(option)
}
就是为了循环的遍历出那15个数组中的数据,x轴是指,所以是value,y轴是类目,于是就是category,
.map这个方法大家可以百度一下,这个方法刚开始的就是将从后台拿到得数据形成了两个新的数组,并且分别赋值x轴和y轴,x轴的data需要放在series中
你学会了吗?
最后放上全代码,关于css我是自己放在index.html中,所以就没有在这个上面,这个大家可以自行设置啦!!!
<!-- 商家销量统计的横向柱状图 -->
<template>
<div class="com-container">
<div class="com-chart" ref="seller_ref"></div>
</div>
</template>
<script>
export default {
data () {
return {
chartInstance: null,
allData: []
}
},
mounted () {
this.initChart()
this.getData()
},
methods: {
initChart () {
this.chartInstance = this.$echarts.init(this.$refs.seller_ref)
},
async getData () {
const { data: res } = await this.$http.get('seller')
console.log(res)
this.allData = res
this.updateChart()
},
updateChart () {
// 循环遍历出x轴的name
const sellerName = this.allData.map((item) => {
return item.name
})
const sellerValue = this.allData.map((item) => {
return item.value
})
const option = {
xAxis: {
type: 'value'
},
yAxis: {
type: 'category',
data: sellerName
},
tooltip: {
// 坐标轴触发
trigger: 'axis',
axisPointer: {
// 鼠标移动到柱状图上,显示为交叉线,
type: 'cross',
label: {
backgroundColor: '#6a7985'
}
}
},
series: [
{
type: 'bar',
data: sellerValue
}
]
}
this.chartInstance.setOption(option)
}
}
}
</script>
<style lang="less" scoped>
</style>
更多推荐
所有评论(0)