文章目錄
- 前言
- 一、組件功能概述
- 二、代碼結構分析
- 2.1 模板結構
- 總結
前言
本文介紹一個基于 Vue 框架的小程序圖表組件開發方案。該組件通過 uCharts
庫實現折線圖的繪制,并支持滾動、縮放、觸摸提示等交互功能。文章將從代碼結構、核心方法、交互實現和樣式設計等方面進行詳細解析。
一、組件功能概述
該組件實現了以下核心功能:
- 動態折線圖繪制
- 圖表滾動交互
- 雙指縮放功能
- 數據點提示框
- 響應式布局適配
二、代碼結構分析
2.1 模板結構
<template><canvascanvas-id="chart"id="chart"@touchstart="touchstart"@touchmove="touchmove"class="charts"@touchend="touchend"/>
</template><script>
import uCharts from '@/js_sdk/u-charts.js'var uChartsInstance = {}export default {data() {return {cWidth: 750,cHeight: 900,options: {}}},onReady() {this.cWidth = uni.upx2px(750)this.cHeight = uni.upx2px(900)},methods: {generateData(data) {if (!data) {console.error('數據未提供,請傳入有效的數據對象。');return;}this.drawCharts('chart', data);},drawCharts(id, data) {try {const min = this.getMin(data.series);const ctx = uni.createCanvasContext(id, this);const chartOptions = {type: 'line',context: ctx,width: this.cWidth,height: this.cHeight,categories: data.categories,series: data.series,animation: true,touchMoveLimit: 24,background: '#FFFFFF',enableScroll: true,scrollPosition: 'current',padding: [15, 15, 0, 5],legend: {},dataLabel: false,xAxis: {disableGrid: true,scrollShow: true,itemCount: 4,labelCount: 2,formatter: (value) => {const [a, b] = value.split(' ');return b.split(':').slice(0, 2).join(':');}},yAxis: {data: [{ min }]},extra: {line: {type: 'straight',width: 2,activeType: 'hollow'},tooltip: {showCategory: true}}};uChartsInstance[id] = new uCharts(chartOptions);} catch (error) {console.error('繪制圖表時發生錯誤:', error);}},getMin(series) {let min = Infinity;series.forEach(item => {item.data.forEach(value => {if (value < min) {min = value;}});});return min;},touchstart(e) {if (uChartsInstance[e.target.id]) {uChartsInstance[e.target.id].scrollStart(e);}},touchmove(e) {if (uChartsInstance[e.target.id]) {uChartsInstance[e.target.id].scroll(e);uChartsInstance[e.target.id].dobuleZoom(e);}},touchend(e) {if (uChartsInstance[e.target.id]) {uChartsInstance[e.target.id].scrollEnd(e);uChartsInstance[e.target.id].touchLegend(e);uChartsInstance[e.target.id].showToolTip(e);}}}
}
</script><style>
page {width: 100%;height: 100%;background: #fff;
}
</style><style lang="scss" scoped>
.charts {width: 750rpx;height: 900rpx;
}
</style>
總結
本文僅僅簡單介紹了ucharts在uniapp微信小程序中的使用。