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>

相关推荐
wuyk55515 小时前
PyQt6-第10讲-PDF工具箱
python·microsoft·pdf·pyqt
鬼手点金19 小时前
缓存作为架构约束
开发语言·前端·人工智能·python·microsoft·缓存·架构
Vic.Tang19 小时前
一次元数据管理项目投标后,我对 Microsoft Purview的初识一
microsoft·purview
贾伟康2 天前
【共创稿事节】第一张服务卡片:2×2 今日菜谱的克制设计
microsoft·harmonyos·arkts·鸿蒙
Shell运维手记2 天前
Shell 结构化命令知识点总结(case、for、while)
运维·microsoft·shell·脚本
2501_944525762 天前
开源鸿蒙平台 KMP_CMP 三方库「Atrium」适配全流程
microsoft·开源·harmonyos
平头哥技术团队2 天前
把端到端延迟当成走时误差:高端腕表主题里的“AI 端渲“
人工智能·microsoft
程序猿追2 天前
连续触摸时,启元 T1 应该怎么回应?一个完整的 ROS 2 交互程序
microsoft·交互
Ai-_Man3 天前
Microsoft Copilot对话数据怎么导入到另外一个Microsoft Copilot账号里去?AI导出鸭
开发语言·javascript·人工智能·microsoft·chatgpt·ecmascript·copilot
镜子AI3 天前
镜子AI工程教程:用Python实现关键词布局检查器与语义改写查重(附完整代码)
人工智能·python·microsoft