uniapp vue3微信小程序echarts 组件封装

在上一篇的基础上,将图表封装成了组件,技术有限,大家凑合着看吧

<template>

<view class="chart-container">

<canvas id="myChart" type="2d" canvas-id="myChart" style="width: 100%; height: 400px;"></canvas>

</view>

</template>

<script setup>

import {

onMounted,

nextTick,

getCurrentInstance,

onUnmounted,

onBeforeUnmount

} from 'vue'

import * as echarts from 'echarts'

let chartInstance = null

const proxy = getCurrentInstance().proxy

const loopInit = () => {

nextTick(() => {

const query = uni.createSelectorQuery().in(proxy)

query.select('#myChart')

.fields({

node: true,

size: true

})

.exec(res => {

// 先判断节点是否获取成功,避免空指针报错

if (!res || !res0) return

const canvas = res0.node

canvas.addEventListener = () => {}

canvas.removeEventListener = () => {}

// 如果后续还遇到类似preventDefault的报错,也可以同步补全

canvas.preventDefault = () => {}

// 从selectorQuery结果中拿到容器的实际宽高

const {

width,

height

} = res0

// 传入小程序环境必需的初始化配置

const chartInstance = echarts.init(canvas, null, {

width: width,

height: height,

devicePixelRatio: uni.getSystemInfoSync().pixelRatio,

useDirtyRect: false, // 小程序环境关闭脏矩形优化,避免兼容问题

useCoarsePointer: true, // 适配移动端触摸交互

pointerSize: 40 // 适配触摸点击的热区大小

})

const option = {

tooltip: {

trigger: 'axis'

},

grid: {

top: '10%',

left: '3%',

right: '4%',

bottom: '20%',

containLabel: true

},

xAxis: {

type: 'category',

data: props.xData

},

yAxis: {

type: 'value'

},

legend: {

data: props.seriesList

},

series: props.seriesList.map(item => ({

name: item.name,

type: 'line', // 线性折线

data: item.data,

smooth: false, // 标准直线,true为平滑曲线

// 区域填充可选

// areaStyle: { opacity: 0.15 }

}))

}

// chartInstance.setOption(option)

/* const option = {

title: { text: '示例图表' },

tooltip: {},

xAxis: { data: 'A', 'B', 'C', 'D', 'E' },

yAxis: {},

series: [{

name: '销量',

type: 'bar',

data: 10, 20, 30, 40, 50

}]

}*/

chartInstance.setOption(option)

})

})

}

const props = defineProps({

xData: {

type: Array,

default: () => \[\]

},

seriesList: {

type: Array,

default: () => \[\]

},

legendlist: {

type: Array,

default: () => \[\]

}

})

onMounted(() => {

nextTick(() => {

// 延迟400ms再启动循环,给组件canvas渲染时间

setTimeout(loopInit, 400)

})

})

</script>

相关推荐
十六年开源服务商13 小时前
2026 WordPress评论增强定制开发深度指南
microsoft
研究员子楚13 小时前
GEO行业发展标准体系白皮书V2.0-第10卷 · 全球篇:跨国标准协同与全球品牌语义治理框架
数据库·人工智能·microsoft·架构·geo
木木子2218 小时前
[特殊字符] 种菜模拟器 — 鸿蒙ArkTS完整技术解析
microsoft·华为·harmonyos
阿里技术2 天前
从 Coder 到 Designer :电商团队数据研发的 Harness Engineering 实践
人工智能·microsoft·机器学习
FreeBuf_2 天前
微软发布创纪录的622个补丁,包含两个正被利用的0Day漏洞
microsoft
狗蛋儿l3 天前
眼见为食GPass眼镜实战
microsoft
abcd_zjq3 天前
Visual studio community 2026 安装缺少 Microsoft.net.4.8.FullRedist.20H2
microsoft·.net·visual studio
北冥you鱼3 天前
Go语言常用包使用指南:从标准库到第三方利器
开发语言·microsoft·golang
祸不单行13 天前
强化学习框架】Miles 项目技术分析---(1)--- 总体
microsoft