2. 安装稍后会使用到的组件:
npm install echarts --save-dev // echarts
npm install axios --save-dev // 一个异步http请求库
3. 新建ChartLine.vue文件用来展示折线图。内容如下:
<template>
<div>
<div>
<button v-on:click="refreshCharts()">刷新</button>
<div class="line" id="line"></div>
</div>
</div>
</template>
<script>
import echarts from 'echarts'
import axios from 'axios'
export default {
name: 'ChartLine',
computed: {
opt () { // option可以参照echarts官方案例
return {
title: {
text: '堆叠区域图'
},
tooltip: {
// 省略, 参数详看echarts官方案例
},
legend: {
data: ['邮件营销']
},
grid: {
// 省略
},
xAxis: [
{
// 省略
data: []
}
],
yAxis: [
// 省略
],
series: [
{
name: '邮件营销',
type: 'line',
data: []
}
]
}
}
},
methods: {
async refreshCharts () {
const res = await axios.get('http://127.0.0.1:8000/api/v1/line')
this.myChart.setOption({ // 更新数据
xAxis: {
data: res.data.legend_data
},
series: {
data: res.data.xAxis_data
}
})
}
},
mounted () {
this.myChart = echarts.init(document.getElementById('line'))
this.myChart.setOption(this.opt) // 初始化echarts
window.addEventListener('resize', this.myChart.resize) // 自适应
}
}
</script>
<style>
.line {
width: 400px;
height: 200px;
margin: 20px auto;
}
</style>
以上代码实现了echarts图表初始化和数据填充的过程,以及点击按钮刷新图表的功能;
4. 注册路由,编辑router/index.js:
import Vue from 'vue'
import Router from 'vue-router'
import ChartLine from '../views/ChartLine.vue'
Vue.use(Router)
export default new Router({
mode: 'history',
routes: [
{
path: '/line',
name: 'Line',
component: ChartLine
}
]
})
5. Gin后台api接口实现:
v1.GET("/line", func(c *gin.Context) {
legendData := []string{"周一", "周二", "周三", "周四", "周五", "周六", "周日"}
xAxisData := []int{120, 240, rand.Intn(500), rand.Intn(500), 150, 230, 180}
c.JSON(200, gin.H{
"legend_data": legendData,
"xAxis_data": xAxisData,
})
})
6. 现在我们就能正确看到图表了,试着点击刷新按钮可以看到图表正确刷新了数据。









