echarts 从后端获取数据,动态渲染图表
简介
echarts的数据是在初始化后setOption中直接填入的,但是很多时候可能数据需要异步加载后再填入。ECharts 中实现异步数据的更新非常简单,在图表初始化后不管任何时候只要通过 jQuery/axios 等工具异步获取数据后通过 setOption 填入数据和配置项就行。
展示
在data(){return{}}中
// echarts配置
option: {
legend: {},
tooltip: {},
dataset: {
source: [
['product', '销售额', '销量'],
['1月', 143.3, 85.8],
['2月', 83.1, 73.4],
['3月', 86.4, 65.2],
['4月', 72.4, 53.9],
['5月', 72.4, 53.9],
['6月', 72.4, 53.9],
['7月', 72.4, 53.9],
['8月', 7, 5],
['9月', 72.4, 5],
['10月', 72.4, 5],
['11月', 72.4, 53.9],
['12月', 72.4, 53.9],
]
// source: []
},
xAxis: {type: 'category'},
yAxis: {},
// Declare several bar series, each will be mapped
// to a column of dataset.source by default.
series: [{
type: 'bar', name: '销量',
}, {type: 'bar', name: '销售额'}]
},
'''
这是一个简单的图表,dataset下的source就是数据原,echars通过这些进行渲染
'''
在methods: {}中
// echarts图表
echartsInit() {
let myChart = this.$echarts.init(document.getElementById('mychart'));
myChart.clear()
myChart.setOption(this.option)
},
// 关键
// 点击按钮从后端获取数据,echarts重新渲染
test() {
this.$axios.get('http://192.168.50.227:8000/api/app/1/test/').then(res => {
this.option.dataset.source = res.data.data
this.echartsInit() // 这步必须要,不然无法重新渲染
})
},
在mounted()中
// 渲染图表
this.echartsInit()
'''
在一开始渲染
'''