赞
踩
在uniapp项目中,我们想要用图表,但是一般的echarts由于代码中存在使用浏览器对象,不能使用,本篇文章推荐使用lime-echart作为图表组件。
项目环境:uniapp vue3 vue-cli
- pnpm add echarts
- -or-
- npm install echarts
引入echarts
- // 全量包 二选一
- import * as echarts from 'echarts'
-
- // 按需引入 二选一
- import * as echarts from 'echarts/core';
- import {LineChart, BarChart} from 'echarts/charts';
- import {TitleComponent,TooltipComponent,GridComponent, DatasetComponent, TransformComponent, LegendComponent } from 'echarts/components';
- // 标签自动布局,全局过渡动画等特性
- import {LabelLayout,UniversalTransition} from 'echarts/features';
- // 引入 Canvas 渲染器,注意引入 CanvasRenderer 是必须的一步
- import {CanvasRenderer} from 'echarts/renderers';
-
- // 按需引入 注册必须的组件
- echarts.use([
- LegendComponent,
- TitleComponent,
- TooltipComponent,
- GridComponent,
- DatasetComponent,
- TransformComponent,
- LineChart,
- BarChart,
- LabelLayout,
- UniversalTransition,
- CanvasRenderer
- ]);
引入lime-echart组件
将l-chart组件添加到components文件夹中,在项目页面中添加组件。
- <template>
- <l-echart></l-echart>
- </template>
- <script setup>
- import LEchart from "@/components/l-echart/l-echart.vue";
- </script>
html
- <template>
- <view>
- <l-echart ref="chartRef"></l-echart>
- </view>
- </template>
script
- import {ref} from 'vue';
- import { onLoad} from "@dcloudio/uni-app";
- import LEchart from "@/components/l-echart/l-echart.vue";
- import * as echarts from "echarts";
-
- const chartRef=ref(null)
-
- onLoad(()=>{
- getDataList().then(()=>{
- initChart(data)
- })
- })
-
- //向后台获取数据
- function getDataList(){
- return new Promise((resolve,reject)=>{
- //TODO
- //你的请求
- })
- }
-
- //初始化图表
- function initChart(data){
- if (data.length == 0) return;
- chartRef.value.init(echarts, chart => {
- chart.setOption(getOption(data));
- });
- }
-
- // 获取图表选项设置
- function getOption(){
- var option = {
- color: ["#F19C91", "#F3D48C", "#F4DFAD"],
- series: [
- {
- name: "form",
- type: "pie",
- minAngle: 30,
- itemStyle: {
- borderColor: "#fff",
- borderWidth: 2,
- borderRadius: 5,
- },
- radius: [30, 60],
- data: data,
- label: {
- position: "inner",
- formatter: function (v) {
- // console.log(v);
- return `{value|${v.percent.toFixed(0)}%}`;
- },
- minMargin: 5,
- edgeDistance: 0,
- lineHeight: 15,
- rich: {
- value: {
- fontFamily: "SourceHanSansCN Bold",
- fontSize: 10,
- color: "#fff",
- },
- },
- },
- }
- ],
- };
- return option;
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。