在uniapp中使用echarts展示图表

官网地址
uni-app插件市场地址
导入插件

image.png

引入使用:
柱图折线图:
image.png

<template>
    <view class='analysis-container'>
        <view class='title'>
            <text>标题</text>
        </view>
        <!-- 图表容器:设置宽度和高度 -->
        <view style="width:600rpx;height:550px;margin-top:20rpx">
            <view style="width:100%;height:180px">
                <l-echart ref="salesChartRef"></l-echart>
            </view>
            <view style="width:100%;height:180px;margin-top:10px">
                <l-echart ref="collectionChartRef"></l-echart>
            </view>
            <view style="width:100%;height:180px;margin-top:10px">
                <l-echart ref="fundsChartRef"></l-echart>
            </view>
        </view>
    </view>
</template>

<script setup>
// 引入 echarts 库
import * as echarts from 'echarts'

// 引入 unibest工具库
import { httpGet } from '@/utils/http'
// 引入数字格式化库
import numeral from 'numeral';

// 获取 DOM 元素的引用(用于初始化图表)
const salesChartRef = ref(null)
const collectionChartRef = ref(null)
const fundsChartRef = ref(null)

// 存储 ECharts 实例
let salesChartInstance = null
let collectionChartInstance = null
let fundsChartInstance = null

let datexAxis = ref([]);//x轴会计期间的时间标记
let saleSamountSeries = ref([]);//图例标点(销售金额)
let collectionSamountSeries = ref([]);//图例标点(回款金额)
let fundsSamountSeries = ref([]);//图例标点(资金金额)
const colors = ['#4080FF', '#3DCBDB', '#ED1919'];

// 销售和回款柱状图配置
const salesOption = {
    color: [colors[0]], // 销售金额颜色
    tooltip: {
        trigger: 'axis',
        axisPointer: {
            type: 'shadow'
        }
    },
    grid: {
        top: '15%',
        bottom: '10%',
        right: '5%',
        left: '12%'
    },
    xAxis: {
        type: 'category',
        axisTick: { show: false },
        data: datexAxis.value,
        axisLine: {
            lineStyle: { type: [10, 20] }
        }
    },
    yAxis: {
        type: 'value',
        name: '销售金额(万元)',
        axisLine: {
            show: true,
            lineStyle: { color: colors[0] }
        }
    },
    series: [{
        name: '销售金额(万元)',
        type: 'bar',
        data: saleSamountSeries.value,
        barWidth: 20,
        label: { show: false }
    }]
}

// 回款柱状图配置
const collectionOption = {
    color: [colors[1]], // 回款金额颜色
    tooltip: {
        trigger: 'axis',
        axisPointer: {
            type: 'shadow'
        }
    },
    grid: {
        top: '15%',
        bottom: '15%',
        right: '5%',
        left: '12%'
    },
    xAxis: {
        type: 'category',
        axisTick: { show: false },
        data: datexAxis.value,
        axisLine: {
            lineStyle: { type: [10, 20] }
        }
    },
    yAxis: {
        type: 'value',
        name: '回款金额(万元)',
        axisLine: {
            show: true,
            lineStyle: { color: colors[1] }
        }
    },
    series: [{
        name: '回款金额(万元)',
        type: 'bar',
        data: collectionSamountSeries.value,
        barWidth: 20,
        label: { show: false }
    }]
}

// 资金折线图配置
const fundsOption = {
    color: [colors[2]], // 资金颜色
    tooltip: {
        trigger: 'axis',
        axisPointer: { type: 'cross' }
    },
    grid: {
        top: '15%',
        bottom: '15%',
        right: '5%',
        left: '12%'
    },
    xAxis: {
        type: 'category',
        axisTick: { show: false },
        data: datexAxis.value,
        axisLine: {
            lineStyle: { type: [10, 20] }
        }
    },
    yAxis: {
        type: 'value',
        name: '资金(万元)',
        axisLine: {
            show: true,
            lineStyle: { color: colors[2] }
        }
    },
    series: [{
        name: '资金(万元)',
        type: 'line',
        smooth: true,
        symbol: 'none',
        data: fundsSamountSeries.value,
        label: { show: false }
    }]
}

// 窗口大小变化时调整图表尺寸
const resizeChart = () => {
    salesChartInstance?.resize()
    fundsChartInstance?.resize()
}

// 组件挂载后执行初始化
onMounted(() => {
    setTimeout(async () => {
        if (!salesChartRef.value || !fundsChartRef.value) return
        
        // 初始化销售图表
        salesChartInstance = await salesChartRef.value.init(echarts)
        salesChartInstance.setOption(salesOption)
        
        // 初始化回款图表
        collectionChartInstance = await collectionChartRef.value.init(echarts)
        collectionChartInstance.setOption(collectionOption)
        
        // 初始化资金图表
        fundsChartInstance = await fundsChartRef.value.init(echarts)
        fundsChartInstance.setOption(fundsOption)
        
        getAnalysisData();
    }, 300)
})

// 获取分析数据
const getAnalysisData = () => {
    var result = httpGet('WebService/GetFunReportDataSource', { productName: "Cust_App_经营分析" }).then((res) => {
        result.value = JSON.parse(res.Data);
        result.value.filter((item) => {
            datexAxis.value.push(item.会计期间);
            item.销售金额 = item.销售金额 > 0 ? numeral(item.销售金额 / 10000).format('0,0.00') : 0;
            saleSamountSeries.value.push(item.销售金额);
            item.回款金额 = item.回款金额 > 0 ? numeral(item.回款金额 / 10000).format('0,0.00') : 0;
            collectionSamountSeries.value.push(item.回款金额);
            item.资金 = item.资金 > 0 ? numeral(item.资金 / 10000).format('0,0.00') : 0;
            fundsSamountSeries.value.push(item.资金);
        })

        // 更新销售图表数据
        salesOption.xAxis.data = datexAxis.value
        salesOption.series[0].data = saleSamountSeries.value
        salesChartInstance?.setOption(salesOption)
        
        // 更新回款图表数据
        collectionOption.xAxis.data = datexAxis.value
        collectionOption.series[0].data = collectionSamountSeries.value
        collectionChartInstance?.setOption(collectionOption)
        
        // 更新资金图表数据
        fundsOption.xAxis.data = datexAxis.value
        fundsOption.series[0].data = fundsSamountSeries.value
        fundsChartInstance?.setOption(fundsOption)
    })
}
</script>
<style lang="scss" scoped>
.analysis-container {
    margin-top: 24rpx;
    background-color: #fff;
    border-radius: 18rpx;
    overflow-y: auto;
    padding: 26rpx 32rpx;
    box-sizing: border-box;

    .title {
        border-radius: 5px 5px 0px 0px;
        height: 30px;
        text-align: left;

        & text {
            height: 20px;
            font-weight: 600;
            font-size: var(--wot-radio-label-fs, var(--wot-checkbox-label-fs, 20px));
            background-image: url("@/static/images/chat/titleBJ.png");
            background-repeat: no-repeat;
            background-size: 100% 60%;
            background-position: 10rpx 20rpx;
        }
    }
}

.profitan-axis {
    width: 100%;
    height: 100%;
}

@media(max-width: 768px) {
    .profitan-axis {
        width: 450;
    }
}

:deep() {
    .echarts-legend-icon {
        width: 12px;
        height: 12px;
        background: none;
        border: none;
    }
}
</style>

饼图:


image.png
<template>
    <view class='product-container'>
        <view class='title'>
            <text>标题</text>
        </view>
        <!-- 图表容器:设置宽度和高度 -->
        <view style="width: 600rpx; height: 350px;margin-top: 20rpx;">
            <l-echart ref="chartRef"></l-echart>
        </view>
    </view>
</template>

<script setup>
import * as echarts from 'echarts'
import { httpGet } from '@/utils/http'
// 获取 DOM 元素的引用(用于初始化图表)
const chartRef = ref(null)
let chartInstance = ref(null);
const option = {
    tooltip: {
        trigger: 'item',
        formatter: (p) => {
            return '名称:' + p.name + '\n占比:' + p.value + '%'
        }
    },
    legend: {
        top: -20,
        right: 20
    },
    series: [
        {
            name: '名称',
            type: 'pie',
            center: ['50%', '58%'],
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            itemStyle: {
                borderRadius: 10,
                borderColor: '#fff',
                borderWidth: 8
            },
            label: {
                show: false,
                position: 'center',
                // format: '{b}: {d}',
                fontSize: 20,
                fontWeight: 'bold',
                formatter: function (params) {
                    const name = params.name;
                    // 每6个字符分割一次
                    const chunkSize = 6;
                    const lines = [];
                    for (let i = 0; i < name.length; i += chunkSize) {
                        lines.push(name.slice(i, i + chunkSize));
                    }
                    return lines.join('\n'); // 换行显示
                }
            },
            emphasis: {
                label: {
                    show: true,
                    fontSize: 20,
                    fontWeight: 'bold'
                }
            },
            labelLine: {
                show: false
            },
            data: []
        }
    ]
};

onMounted(() => {
    // 组件能被调用必须是组件的节点已经被渲染到页面上
    nextTick(async () => {
        if (!chartRef.value) return
        chartInstance = await chartRef.value.init(echarts)
        chartInstance.setOption(option)
        getProductData();
    })
})

// 获取分析数据
const getProductData = () => {
    // 增加登录逻辑,获取到登录用户所用的数据库Id
    var result = httpGet('WebService/GetFunReportDataSource', { productName: "cust_app_产品分布" }).then((res) => {
        result.value = JSON.parse(res.Data);
        const seriesdata = [];//组装图例所用的数据
        result.value.forEach(item => {
            if (item.占比.endsWith('%'))
                item.占比 = parseFloat(item.占比)
            var data = { name: item.名称, value: item.占比 };
            seriesdata.push(data);
        });
        option.series[0].data = seriesdata;
        chartInstance?.setOption(option);
    })
}
</script>
<style lang="scss" scoped>
.product-container {
    margin-top: 24rpx;
    background-color: #fff;
    border-radius: 18rpx;
    overflow-y: auto;
    padding: 26rpx 32rpx;
    box-sizing: border-box;

    .title {
        border-radius: 5px 5px 0px 0px;
        height: 30px;
        text-align: left;

        & text {
            height: 20px;
            font-weight: 600;
            font-size: var(--wot-radio-label-fs, var(--wot-checkbox-label-fs, 20px));
            background-image: url("@/static/images/chat/titleBJ.png");
            background-repeat: no-repeat;
            background-size: 100% 60%;
            background-position: 10rpx 20rpx;
        }
    }
}
</style>
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容