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>

相关推荐
程序猿小玉兒19 小时前
Quartz定时任务偶尔不执行
服务器·windows·microsoft
qq_366624782 天前
在线PDF翻译工具在多语言技术文档处理中的实战应用
microsoft·pdf
冷咖啡离 我的笨笨2 天前
从Win8回顾微软平台的各种技术
microsoft
ACP广源盛139246256733 天前
DeepSeek‑V4‑Flash 公测@ACP#昇腾 950 国产算力组合落地,国产 PCIe 交换芯片 IX9104 有哪些硬件机会
大数据·数据库·人工智能·分布式·单片机·嵌入式硬件·microsoft
波罗丁牌3 天前
逆变与协变详解
windows·microsoft
'pi%'3 天前
多 Agent 协同方案实践:基于 LangGraph 搭建能源领域智能调度工作流
人工智能·爬虫·microsoft·langchain·ocr·能源
意图共鸣3 天前
意图共鸣科技 · 底色定调书
人工智能·microsoft
hhb_6183 天前
全方位综合能力AI智能体专项测试技术文档
人工智能·microsoft
编码者卢布3 天前
【Azure APIM】通过 API Management 公开API为 MCP Server 的试验 (二)
microsoft·flask·azure
海盗12343 天前
微软技术周报 ——2026-08-03
后端·python·microsoft·c#·.netcore