Uniapp Echarts 图表:从后端 API 获取数据并渲染示例
<template>
<div class='chart-container'>
<ec-canvas ref='canvas' :canvas-id='canvasId' :ec='ec'></ec-canvas>
</div>
</template>
<script>
import * as echarts from 'echarts';
import { getChartData } from '@/api/chart'; // 假设这是一个用于从API获取数据的方法
export default {
data() {
return {
canvasId: 'my-chart',
ec: {
lazyLoad: true,
},
chartData: {}, // 存储图表数据
};
},
mounted() {
this.getChartData();
},
methods: {
async getChartData() {
try {
const res = await getChartData(); // 调用API获取数据
this.chartData = res.data; // 将数据存储在组件中
this.renderChart(); // 渲染图表
} catch (error) {
console.log(error);
}
},
renderChart() {
const chart = echarts.init(this.$refs.canvas); // 初始化echarts实例
chart.setOption(this.chartData); // 设置图表数据
},
},
};
</script>
<style>
.chart-container {
width: 100%;
height: 500px;
}
</style>
原文地址: https://www.cveoy.top/t/topic/mVSz 著作权归作者所有。请勿转载和采集!