vue中echart前后端数据交互
时间: 2023-11-20 16:58:54 浏览: 150
在Vue中使用Echarts进行前后端数据交互,可以通过以下步骤实现:
1.在Vue项目中安装Echarts
```shell
npm install echarts --save
```
2.在Vue组件中引入Echarts
```javascript
import echarts from 'echarts'
```
3.在Vue组件中创建一个Echarts实例
```javascript
mounted() {
// 基于准备好的dom,初始化echarts实例
let myChart = echarts.init(document.getElementById('myChart'))
// 指定图表的配置项和数据
let option = {
title: {
text: 'ECharts 入门示例'
},
tooltip: {},
legend: {
data:['销量']
},
xAxis: {
data: ["衬衫","羊毛衫","雪纺衫","裤子","高跟鞋","袜子"]
},
yAxis: {},
series: [{
name: '销量',
type: 'bar',
data: [5, 20, 36, 10, 10, 20]
}]
}
// 使用刚指定的配置项和数据显示图表。
myChart.setOption(option)
}
```
4.在Vue组件中使用axios获取后端数据
```javascript
import axios from 'axios'
export default {
data() {
return {
chartData: []
}
},
mounted() {
axios.get('/api/chartData')
.then(res => {
this.chartData = res.data
this.renderChart()
})
.catch(err => {
console.log(err)
})
},
methods: {
renderChart() {
let myChart = echarts.init(document.getElementById('myChart'))
let option = {
title: {
text: 'ECharts 入门示例'
},
tooltip: {},
legend: {
data:['销量']
},
xAxis: {
data: this.chartData.categories
},
yAxis: {},
series: [{
name: '销量',
type: 'bar',
data: this.chartData.data
}]
}
myChart.setOption(option)
}
}
}
```
5.在后端使用koa2编写接口,返回数据给前端
```javascript
const Koa = require('koa')
const Router = require('koa-router')
const app = new Koa()
const router = new Router()
router.get('/api/chartData', async (ctx, next) => {
const chartData = {
categories: ['衬衫', '羊毛衫', '雪纺衫', '裤子', '高跟鞋', '袜子'],
data: [5, 20, 36, 10, 10, 20]
}
ctx.body = chartData
})
app.use(router.routes()).use(router.allowedMethods())
app.listen(3000, () => {
console.log('server is running at http://localhost:3000')
})
```
阅读全文