首先是安装Echarts
yarn add echarts 或者npm install echarts
在组件中引入 Echarts
在需要使用图表的 Vue 组件中引入 Echarts:
import * as echarts from 'echarts';
创建一个 DOM 元素用于渲染图表在组件的模板中创建一个 DOM 元素,例如一个 <div>
元素,用于承载图表:
<div ref="chartDom"></div>
- 初始化图表
在组件的mounted
生命周期钩子中初始化图表:写在method方法里mounted() { this.fetchInventoryData(); this.initInventoryChart(); // 调用初始化图表的方法 }
-
前端处理后端传过来数据的方法
fetchInventoryData() {
// axios.get('/system/inventory/getInventoryDataForEcharts')
maplist()
.then(response => {
console.log('原始响应:', response);
return response;
})
.then(data => {
console.log('Received data:', data);
const receivedData = data;
console.log('Received inventoryNumbers:', receivedData.inventoryNumbers);
console.log('Received quantities:', receivedData.quantities);
this.inventoryData = receivedData.inventoryNumbers.map((invId, index) => {
console.log(`Current index: ${index}, invId: ${invId}, quantity: ${receivedData.quantities[index]}`);
return {
inventoryNumber: invId,
quantity: receivedData.quantities[index]
};
});
console.log('Mapped inventoryData:', this.inventoryData);
this.initInventoryChart();//不加这个下面的逻辑会走不通的,异步处理错误
})
.catch(error => {
console.error('Error fetching inventory data:', error);
});
},
initInventoryChart() {
console.log('进入 initInventoryChart 方法');
console.log('当前的 inventoryData:', this.inventoryData);
// 确保获取到库存数据后再初始化图表
if (this.inventoryData && this.inventoryData.length > 0) {
const chartDom = document.getElementById('inventoryChart');
this.myChart = echarts.init(chartDom);
const option = {
title: {
text: '库存分布'
},
tooltip: {
trigger: 'item'
},
legend: {
orient:'vertical',
left: 'left'
},
series: [
{
name: '库存分布',
type: 'pie',
radius: '50%',
data: this.inventoryData.map(item => ({
name: `库存 ${item.inventoryNumber}`,
value: item.quantity
})),
emphasis: {
itemStyle: {
shadowBlur: 10,
shadowOffsetX: 0,
shadowColor: 'rgba(0, 0, 0, 0.5)'
}
}
}
]
};
this.myChart.setOption(option);
}
},
引用js
import{maplist} from '@/api/system/inventory';
JS
export function maplist(){
return request({
url:'/system/inventory/getInventoryDataForEcharts',//路径写你们自己的,引用那里也一样
method:'get',
})
}
基本上前端就可以了
接下来是后端Controller层
@RequestMapping("/getInventoryDataForEcharts")
public Map<String, Object> getInventoryDataForEcharts() {
List<YlInventory> inventoryList = ylInventoryService.selectYlInventoryList(new YlInventory());
List<Long> inventoryNumbers = new ArrayList<>();
List<Long> quantities = new ArrayList<>();
for (YlInventory inventory : inventoryList) {
inventoryNumbers.add(inventory.getInvId());
quantities.add(inventory.getAmount());
}
Map<String, Object> result = new HashMap<>();
result.put("inventoryNumbers", inventoryNumbers);
result.put("quantities", quantities);
return result;
}
调用的是selectYlInvenList这个方法,这个方法就是个查询列表的方法,跟查询走的是一个方法。本质都是通过调用这个方法,获取数据库的数据,返回给前端。