| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919 |
- <template>
- <CustomNav title="体重" leftType="back" />
- <view class="page">
- <view class="header">
- <view class="month-selector">
- <button class="btn" @click="prevPeriod">‹</button>
- <view class="period-controls">
- <picker mode="multiSelector" :value="pickerValue" :range="pickerRange" @change="onPickerChange">
- <view class="month-label">{{ displayPeriod }}</view>
- </picker>
- <view class="view-toggle">
- <button :class="['toggle-btn', { active: viewMode === 'month' }]" @click="setViewMode('month')">月</button>
- <button :class="['toggle-btn', { active: viewMode === 'week' }]" @click="setViewMode('week')">周</button>
- </view>
- </view>
- <button class="btn" @click="nextPeriod">›</button>
- </view>
- </view>
- <!-- 趋势图 - 简化canvas设置 -->
- <view class="chart-wrap">
- <view class="chart-header">本月趋势</view>
- <canvas
- canvas-id="weightChart"
- id="weightChart"
- class="chart-canvas"
- :style="{ width: canvasWidth + 'px', height: canvasHeight + 'px' }"
- ></canvas>
- </view>
- <!-- 其他内容保持不变 -->
- <view class="content">
- <view class="summary">共 {{ records.length }} 条记录,本月平均:{{ averageWeight }} kg</view>
- <view class="list">
- <view v-if="records.length === 0" class="empty">暂无记录,点击右下角 + 添加</view>
- <view v-for="item in records" :key="item.id" class="list-item">
- <view class="date">{{ item.date }}</view>
- <view class="value">{{ item.weight }} kg</view>
- <button class="btn-delete" @click="confirmDeleteRecord(item.id)">✕</button>
- </view>
- </view>
- </view>
- <view class="fab" @click="openAdd">
- <view class="fab-inner">+</view>
- </view>
- <view class="modal" v-if="showAdd">
- <view class="modal-backdrop" @click="closeAdd"></view>
- <view class="modal-panel">
- <view class="drag-handle"></view>
- <view class="modal-header"><text class="modal-title">添加体重</text></view>
- <view class="modal-inner">
- <view class="form-row">
- <text class="label">日期</text>
- <picker mode="date" :value="addDate" @change="onAddDateChange">
- <view class="picker-display">{{ addDateLabel }}</view>
- </picker>
- </view>
- <view class="form-row">
- <text class="label">体重 (kg)</text>
- <input type="number" v-model.number="addWeight" class="input" placeholder="请输入体重" />
- </view>
- </view>
- <view class="ruler-wrap">
- <ScaleRuler v-if="showAdd" :min="20" :max="200" :step="0.1" :gutter="20" :initialValue="addWeight ?? 65" @update="onAddRulerUpdate" @change="onAddRulerChange" />
- </view>
- <view class="fixed-footer">
- <button class="btn-primary btn-full" @click="confirmAdd">保存</button>
- </view>
- </view>
- </view>
- </view>
- <TabBar />
- </template>
- <script setup lang="ts">
- import { ref, computed, onMounted, watch, nextTick, onBeforeUnmount, getCurrentInstance } from 'vue'
- import uCharts from '@qiun/ucharts'
- import CustomNav from '@/components/custom-nav.vue'
- import TabBar from '@/components/tab-bar.vue'
- import ScaleRuler from '@/components/scale-ruler.vue'
- import { getWeekStart, getWeekEnd, getWeekNumber, formatDisplayDate, formatPickerDate, daysInMonth, weekDayIndex } from '@/utils/date'
- type RecordItem = { id: string; date: string; weight: number }
- // 当前展示年月
- const current = ref(new Date())
- const pickerValue = ref([current.value.getFullYear() - 2000, current.value.getMonth()]) // 年从2000年开始,月0-11
- // 视图模式:'month' 或 'week'
- const viewMode = ref<'month' | 'week'>('month')
- // 年月选择器的选项范围
- const pickerRange = ref([
- Array.from({ length: 50 }, (_, i) => `${2000 + i}年`), // 2000-2049年
- Array.from({ length: 12 }, (_, i) => `${i + 1}月`) // 1-12月
- ])
- // 明确的canvas尺寸(将由 getCanvasSize 初始化以匹配设备宽度)
- const canvasWidth = ref(700) // 初始值,会在 mounted 时覆盖
- const canvasHeight = ref(280)
- // 获取Canvas实际尺寸的函数 - 参考微信小程序示例使用固定尺寸
- function getCanvasSize(): Promise<{ width: number; height: number }> {
- return new Promise((resolve) => {
- // 使用固定尺寸,参考微信小程序示例
- const windowWidth = uni.getSystemInfoSync().windowWidth;
- const width = windowWidth; // 占满屏幕宽度
- const height = 280 / 750 * windowWidth; // 280rpx转换为px,与CSS高度匹配
- resolve({ width, height });
- });
- }
- // 使用 formatPickerDate 从 src/utils/date.ts
- const displayYear = computed(() => current.value.getFullYear())
- const displayMonth = computed(() => current.value.getMonth() + 1)
- // 显示周期的计算属性
- const displayPeriod = computed(() => {
- if (viewMode.value === 'month') {
- return `${displayYear.value}年 ${displayMonth.value}月`
- } else {
- const weekStart = getWeekStart(current.value)
- const weekEnd = getWeekEnd(current.value)
- return `${formatDisplayDate(weekStart)} - ${formatDisplayDate(weekEnd)}`
- }
- })
- const records = ref<RecordItem[]>(generateMockRecords(current.value))
- function generateMockRecords(d: Date): RecordItem[] {
- const arr: RecordItem[] = []
- let daysCount: number
- if (viewMode.value === 'month') {
- const y = d.getFullYear()
- const m = d.getMonth()
- daysCount = daysInMonth(y, m)
- } else {
- daysCount = 7
- }
- const n = Math.floor(Math.random() * Math.min(daysCount, 7))
- for (let i = 0; i < n; i++) {
- let recordDate: Date
- if (viewMode.value === 'month') {
- const y = d.getFullYear()
- const m = d.getMonth()
- const day = Math.max(1, Math.floor(Math.random() * daysCount) + 1)
- recordDate = new Date(y, m, day)
- } else {
- const weekStart = getWeekStart(d)
- const dayOffset = Math.floor(Math.random() * 7)
- recordDate = new Date(weekStart)
- recordDate.setDate(weekStart.getDate() + dayOffset)
- }
- arr.push({
- id: `${recordDate.getTime()}${i}${Date.now()}`,
- date: formatDisplayDate(recordDate),
- weight: Number((50 + Math.random() * 50).toFixed(1))
- })
- }
- return arr.sort((a, b) => (a.date < b.date ? 1 : -1))
- }
- // 将 records 聚合为每天一个点(取最新记录)
- function aggregateDaily(recordsArr: RecordItem[], year: number, month: number) {
- const map = new Map<number, RecordItem>()
- for (const r of recordsArr) {
- const parts = r.date.split('-')
- if (parts.length >= 3) {
- const y = parseInt(parts[0], 10)
- const m = parseInt(parts[1], 10) - 1
- const d = parseInt(parts[2], 10)
- if (y === year && m === month) {
- // 覆盖同一天,保留最新的(数组头部为最新)
- map.set(d, r)
- }
- }
- }
- // 返回按日索引的数组
- return map
- }
- const averageWeight = computed(() => {
- if (records.value.length === 0) return '--'
- const sum = records.value.reduce((s, r) => s + r.weight, 0)
- return (sum / records.value.length).toFixed(1)
- })
- // 使用共享日期工具 (src/utils/date.ts)
- // Canvas / uCharts 绘图 - 修复版本
- const chartInstance = ref<any>(null)
- const vm = getCurrentInstance()
- let chartInitialized = false
- let chartBusy = false // 绘图锁,防止并发初始化/更新
- // 简化的图表绘制函数(支持月/周视图)
- async function drawChart() {
- if (chartBusy) return
- chartBusy = true
- if (chartInitialized && chartInstance.value) {
- try { await updateChartData() } finally { chartBusy = false }
- return
- }
- if (chartInstance.value) {
- try { if (chartInstance.value.destroy) chartInstance.value.destroy() } catch (e) { console.warn('Destroy chart error:', e) }
- chartInstance.value = null
- }
- if (typeof uCharts === 'undefined') { console.warn('uCharts not available'); return }
- const size = await getCanvasSize()
- const cssWidth = size.width
- const cssHeight = size.height
- const pixelRatio = 1
- const rightGap = Math.max(24, Math.round(cssWidth * 0.04))
- const chartWidth = Math.max(cssWidth - rightGap, Math.round(cssWidth * 0.85))
- const year = current.value.getFullYear()
- const month = current.value.getMonth()
- // categories 构造,区分月/周视图
- const categories: string[] = []
- if (viewMode.value === 'month') {
- const days = daysInMonth(year, month)
- const showLabelDays: number[] = []
- if (days > 0) {
- showLabelDays.push(1)
- if (days > 1) showLabelDays.push(days)
- if (days > 7) showLabelDays.push(Math.ceil(days / 3))
- if (days > 14) showLabelDays.push(Math.ceil(days * 2 / 3))
- }
- for (let d = 1; d <= days; d++) categories.push(showLabelDays.includes(d) ? `${d}日` : '')
- } else {
- const weekStart = getWeekStart(current.value)
- const weekDays = ['一', '二', '三', '四', '五', '六', '日']
- for (let i = 0; i < 7; i++) {
- const date = new Date(weekStart)
- date.setDate(weekStart.getDate() + i)
- categories.push(`${date.getDate()}日(${weekDays[i]})`)
- }
- }
- // 聚合数据
- const data: number[] = []
- const filteredCategories: string[] = []
- const dayMap = new Map<number, RecordItem>()
- if (viewMode.value === 'month') {
- for (const r of records.value) {
- const parts = r.date.split('-')
- if (parts.length >= 3) {
- const y = parseInt(parts[0], 10)
- const m = parseInt(parts[1], 10) - 1
- const d = parseInt(parts[2], 10)
- if (y === year && m === month) dayMap.set(d, r)
- }
- }
- const sortedDays = Array.from(dayMap.keys()).sort((a, b) => a - b)
- for (const d of sortedDays) { const rec = dayMap.get(d)!; filteredCategories.push(`${d}日`); data.push(rec.weight) }
- } else {
- const weekStart = getWeekStart(current.value)
- for (const r of records.value) {
- const parts = r.date.split('-')
- if (parts.length >= 3) {
- const recordDate = new Date(parseInt(parts[0], 10), parseInt(parts[1], 10) - 1, parseInt(parts[2], 10))
- const weekStartDate = getWeekStart(recordDate)
- if (weekStartDate.getTime() === weekStart.getTime()) {
- const dayOfWeek = recordDate.getDay() || 7
- dayMap.set(dayOfWeek, r)
- }
- }
- }
- const weekDays = ['一','二','三','四','五','六','日']
- for (let i = 1; i <= 7; i++) {
- const rec = dayMap.get(i)
- if (rec) { const date = new Date(rec.date); filteredCategories.push(`${date.getDate()}日(${weekDays[i-1]})`); data.push(rec.weight) }
- }
- }
- const categoriesToUse = filteredCategories.length ? filteredCategories : categories
- const validData = data.filter(v => v > 0)
- const minVal = validData.length ? Math.floor(Math.min(...validData)) - 2 : 40
- const maxVal = validData.length ? Math.ceil(Math.max(...validData)) + 2 : 100
- const series = [{ name: '体重', data: data, color: '#ff6a00' }]
- // 获取 canvas 上下文
- let ctx: any = null
- try {
- if (typeof uni !== 'undefined' && typeof uni.createCanvasContext === 'function') {
- try { ctx = vm?.proxy ? uni.createCanvasContext('weightChart', vm.proxy) : uni.createCanvasContext('weightChart') } catch (e) { try { ctx = uni.createCanvasContext('weightChart') } catch (err) { ctx = null } }
- }
- } catch (e) { ctx = null }
- if (!ctx && typeof document !== 'undefined') {
- try {
- let el: HTMLCanvasElement | null = null
- for (let attempt = 0; attempt < 3; attempt++) {
- el = document.getElementById('weightChart') as HTMLCanvasElement | null
- if (el) break
- await new Promise(r => setTimeout(r, 50))
- }
- if (el && el.getContext) {
- try {
- const physicalW = Math.floor(cssWidth * pixelRatio)
- const physicalH = Math.floor(cssHeight * pixelRatio)
- if (el.width !== physicalW || el.height !== physicalH) { el.width = physicalW; el.height = physicalH; el.style.width = cssWidth + 'px'; el.style.height = cssHeight + 'px' }
- } catch (e) { console.warn('Set canvas physical size failed', e) }
- ctx = el.getContext('2d')
- }
- } catch (e) { ctx = null }
- }
- if (!ctx) { console.warn('Unable to obtain canvas context for uCharts.'); return }
- const config = {
- $this: vm?.proxy,
- canvasId: 'weightChart',
- context: ctx,
- type: 'line',
- fontSize: 10,
- categories: categoriesToUse,
- series: series,
- width: chartWidth,
- padding: [10, rightGap + 8, 18, 10],
- height: cssHeight,
- pixelRatio,
- background: 'transparent',
- animation: false,
- enableScroll: false,
- dataLabel: false,
- legend: { show: false },
- xAxis: { disableGrid: true, axisLine: true, axisLineColor: '#e0e0e0', fontColor: '#666666', fontSize: 10, boundaryGap: 'justify' },
- yAxis: { disableGrid: false, gridColor: '#f5f5f5', splitNumber: 4, min: minVal, max: maxVal, axisLine: true, axisLineColor: '#e0e0e0', fontColor: '#666666', fontSize: 10, format: (val: number) => val % 1 === 0 ? `${val}kg` : '' },
- extra: { line: { type: 'curve', width: 1, activeType: 'point', point: { radius: 0.5, strokeWidth: 0.5 } }, tooltip: { showBox: false, showCategory: false } }
- }
- try {
- if (chartInstance.value && chartInstance.value.destroy) { try { chartInstance.value.destroy() } catch (e) { console.warn('destroy before init failed', e) } chartInstance.value = null; chartInitialized = false }
- chartInstance.value = new uCharts(config)
- chartInitialized = true
- } catch (error) { console.error('uCharts init error:', error); chartInitialized = false }
- chartBusy = false
- }
- // 更新数据而不重新初始化
- async function updateChartData() {
- if (chartBusy) return
- chartBusy = true
- if (!chartInstance.value || !chartInitialized) {
- try {
- await drawChart()
- } finally {
- chartBusy = false
- }
- return
- }
- const year = current.value.getFullYear()
- const month = current.value.getMonth()
- const categories: string[] = []
- const data: number[] = []
- const filteredCategories: string[] = []
- const dayMap = new Map<number, RecordItem>()
- if (viewMode.value === 'month') {
- const days = daysInMonth(year, month)
- const showLabelDays: number[] = []
- if (days > 0) {
- showLabelDays.push(1)
- if (days > 1) showLabelDays.push(days)
- if (days > 7) showLabelDays.push(Math.ceil(days / 3))
- if (days > 14) showLabelDays.push(Math.ceil(days * 2 / 3))
- }
- for (let d = 1; d <= days; d++) categories.push(showLabelDays.includes(d) ? `${d}日` : '')
- for (const r of records.value) {
- const parts = r.date.split('-')
- if (parts.length >= 3) {
- const y = parseInt(parts[0], 10)
- const m = parseInt(parts[1], 10) - 1
- const d = parseInt(parts[2], 10)
- if (y === year && m === month) dayMap.set(d, r)
- }
- }
- const sortedDays = Array.from(dayMap.keys()).sort((a, b) => a - b)
- for (const d of sortedDays) { const rec = dayMap.get(d)!; filteredCategories.push(`${d}日`); data.push(rec.weight) }
- } else {
- const weekStart = getWeekStart(current.value)
- const weekDays = ['一','二','三','四','五','六','日']
- for (let i = 0; i < 7; i++) {
- const date = new Date(weekStart)
- date.setDate(weekStart.getDate() + i)
- categories.push(`${date.getDate()}日(${weekDays[i]})`)
- }
- for (const r of records.value) {
- const parts = r.date.split('-')
- if (parts.length >= 3) {
- const recordDate = new Date(parseInt(parts[0], 10), parseInt(parts[1], 10) - 1, parseInt(parts[2], 10))
- const weekStartDate = getWeekStart(recordDate)
- if (weekStartDate.getTime() === weekStart.getTime()) {
- const dayOfWeek = recordDate.getDay() || 7
- dayMap.set(dayOfWeek, r)
- }
- }
- }
- for (let i = 1; i <= 7; i++) {
- const rec = dayMap.get(i)
- if (rec) { const date = new Date(rec.date); filteredCategories.push(`${date.getDate()}日(${weekDays[i-1]})`); data.push(rec.weight) }
- }
- }
- const categoriesToUse = filteredCategories.length ? filteredCategories : categories
- const validData = data.filter(v => v > 0)
- const minVal = validData.length ? Math.floor(Math.min(...validData)) - 2 : 40
- const maxVal = validData.length ? Math.ceil(Math.max(...validData)) + 2 : 100
- try {
- try {
- const size = await getCanvasSize()
- const cssWidth = size.width
- const rightGap = Math.max(24, Math.round(cssWidth * 0.04))
- const chartWidth = Math.max(cssWidth - rightGap, Math.round(cssWidth * 0.85))
- if (chartInstance.value.opts) {
- chartInstance.value.opts.width = chartWidth
- chartInstance.value.opts.padding = [10, rightGap + 8, 18, 10]
- }
- } catch (e) {}
- chartInstance.value.updateData({ categories: categoriesToUse, series: [{ name: '体重', data: data, color: '#ff6a00' }] })
- chartInstance.value.opts.yAxis.min = minVal
- chartInstance.value.opts.yAxis.max = maxVal
- } catch (error) {
- console.error('Update chart error:', error)
- try { if (chartInstance.value && chartInstance.value.destroy) chartInstance.value.destroy() } catch (e) { console.warn('destroy on update failure failed', e) }
- chartInstance.value = null
- chartInitialized = false
- try { await drawChart() } catch (e) { console.error('re-init after update failure also failed', e) }
- }
- chartBusy = false
- }
- onMounted(() => {
- // 延迟确保DOM渲染完成
- setTimeout(async () => {
- await nextTick()
- // 由 getCanvasSize 计算并覆盖 canvasWidth/canvasHeight(确保模板样式和绘图一致)
- try {
- const size = await getCanvasSize()
- canvasWidth.value = size.width
- canvasHeight.value = size.height
- } catch (e) {
- console.warn('getCanvasSize failed on mounted', e)
- }
- await drawChart()
- }, 500)
- })
- // 简化监听,避免频繁重绘
- watch([() => current.value], async () => {
- setTimeout(async () => {
- await updateChartData()
- }, 100)
- })
- watch([() => records.value], async () => {
- setTimeout(async () => {
- await updateChartData()
- }, 100)
- }, { deep: true })
- onBeforeUnmount(() => {
- if (chartInstance.value && chartInstance.value.destroy) {
- try {
- chartInstance.value.destroy()
- } catch (e) {
- console.warn('uCharts destroy error:', e)
- }
- }
- chartInstance.value = null
- chartInitialized = false
- })
- // 强制重建图表(用于切换月份时彻底刷新,如同退出页面再进入)
- async function rebuildChart() {
- // 如果正在绘制,等一小会儿再销毁
- if (chartBusy) {
- // 等待最大 300ms,避免长时间阻塞
- await new Promise(r => setTimeout(r, 50))
- }
- try {
- if (chartInstance.value && chartInstance.value.destroy) {
- try { chartInstance.value.destroy() } catch (e) { console.warn('destroy in rebuildChart failed', e) }
- }
- } catch (e) {
- console.warn('rebuildChart destroy error', e)
- }
- chartInstance.value = null
- chartInitialized = false
- // 等待 DOM/Tick 稳定
- await nextTick()
- // 重新初始化
- try {
- await drawChart()
- } catch (e) {
- console.error('rebuildChart drawChart failed', e)
- }
- }
- // 周/月切换和周期导航
- async function prevPeriod() {
- const d = new Date(current.value)
- if (viewMode.value === 'month') {
- d.setMonth(d.getMonth() - 1)
- } else {
- d.setDate(d.getDate() - 7)
- }
- current.value = d
- pickerValue.value = [d.getFullYear() - 2000, d.getMonth()]
- records.value = generateMockRecords(d)
- await rebuildChart()
- }
- async function nextPeriod() {
- const d = new Date(current.value)
- if (viewMode.value === 'month') {
- d.setMonth(d.getMonth() + 1)
- } else {
- d.setDate(d.getDate() + 7)
- }
- current.value = d
- pickerValue.value = [d.getFullYear() - 2000, d.getMonth()]
- records.value = generateMockRecords(d)
- await rebuildChart()
- }
- async function setViewMode(mode: 'month' | 'week') {
- if (viewMode.value !== mode) {
- viewMode.value = mode
- records.value = generateMockRecords(current.value)
- await rebuildChart()
- }
- }
- async function onPickerChange(e: any) {
- const val = e?.detail?.value || e
- if (Array.isArray(val) && val.length >= 2) {
- const y = 2000 + val[0]
- const m = val[1]
- const d = new Date(y, m, 1)
- current.value = d
- pickerValue.value = [val[0], val[1]]
- records.value = generateMockRecords(d)
- await rebuildChart()
- }
- }
- // 添加逻辑保持不变
- const showAdd = ref(false)
- const addDate = ref(formatPickerDate(new Date()))
- const addDateLabel = ref(formatDisplayDate(new Date()))
- const addWeight = ref<number | null>(null)
- function onAddRulerUpdate(val: number) {
- addWeight.value = Number(val.toFixed(1))
- }
- function onAddRulerChange(val: number) {
- addWeight.value = Number(val.toFixed(1))
- }
- function openAdd() {
- showAdd.value = true
- if (!addWeight.value) addWeight.value = 65
- }
- function closeAdd() {
- showAdd.value = false
- addWeight.value = null
- }
- function onAddDateChange(e: any) {
- const val = e?.detail?.value || e
- addDate.value = val
- addDateLabel.value = val.replace(/^(.{10}).*$/, '$1')
- }
- async function confirmAdd() {
- if (!addWeight.value) {
- uni.showToast && uni.showToast({ title: '请输入体重', icon: 'none' })
- return
- }
- const id = `user-${Date.now()}`
- const item: RecordItem = { id, date: addDateLabel.value, weight: Number(Number(addWeight.value).toFixed(1)) }
- const parts = addDate.value.split('-')
- const addY = parseInt(parts[0], 10)
- const addM = parseInt(parts[1], 10) - 1
- if (addY === current.value.getFullYear() && addM === current.value.getMonth()) {
- records.value = [item, ...records.value]
- }
- uni.showToast && uni.showToast({ title: '已添加', icon: 'success' })
- closeAdd()
- // 新增记录后彻底重建图表,确保像退出再进入一样刷新
- try {
- await rebuildChart()
- } catch (e) {
- console.warn('rebuildChart after add failed', e)
- }
- }
- async function confirmDeleteRecord(id: string) {
- if (typeof uni !== 'undefined' && uni.showModal) {
- uni.showModal({
- title: '删除',
- content: '确认删除该条记录吗?',
- success: async (res: any) => {
- if (res.confirm) {
- records.value = records.value.filter(r => r.id !== id)
- try { await rebuildChart() } catch (e) { console.warn('rebuildChart after delete failed', e) }
- }
- }
- })
- } else {
- records.value = records.value.filter(r => r.id !== id)
- try { await rebuildChart() } catch (e) { console.warn('rebuildChart after delete failed', e) }
- }
- }
- </script>
- <style scoped>
- .page {
- min-height: calc(100vh);
- padding-top: calc(var(--status-bar-height) + 44px);
- background: #f5f6f8;
- box-sizing: border-box
- }
- .header {
- padding: 20rpx 40rpx
- }
- .month-selector {
- display: flex;
- align-items: center;
- justify-content: center;
- gap: 12rpx
- }
- .period-controls {
- display: flex;
- flex-direction: column;
- align-items: center;
- gap: 8rpx;
- }
- .view-toggle {
- display: flex;
- gap: 4rpx;
- }
- .toggle-btn {
- padding: 4rpx 12rpx;
- border: 1rpx solid #ddd;
- background: #f5f5f5;
- color: #666;
- border-radius: 6rpx;
- font-size: 24rpx;
- min-width: 60rpx;
- text-align: center;
- }
- .toggle-btn.active {
- background: #ff6a00;
- color: #fff;
- border-color: #ff6a00;
- }
- .month-label {
- font-size: 34rpx;
- color: #333
- }
- .btn {
- background: transparent;
- border: none;
- font-size: 36rpx;
- color: #666
- }
- .content {
- padding: 20rpx 24rpx 100rpx 24rpx
- }
- .chart-wrap {
- background: #fff;
- border-radius: 12rpx;
- padding: 24rpx;
- margin: 0 24rpx 20rpx 24rpx;
- box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.03)
- }
- .chart-header {
- font-size: 32rpx;
- color: #333;
- margin-bottom: 20rpx;
- font-weight: 600
- }
- /* 关键修复:确保canvas样式正确,参考微信小程序示例 */
- .chart-canvas {
- width: 750rpx;
- height: 280rpx;
- background-color: #FFFFFF;
- display: block;
- }
- .summary {
- padding: 20rpx;
- color: #666;
- font-size: 28rpx
- }
- .list {
- background: #fff;
- border-radius: 12rpx;
- padding: 10rpx;
- box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.03)
- }
- .empty {
- padding: 40rpx;
- text-align: center;
- color: #999
- }
- .list-item {
- display: flex;
- align-items: center;
- padding: 20rpx;
- border-bottom: 1rpx solid #f0f0f0
- }
- .list-item .date {
- color: #666
- }
- .list-item .value {
- color: #333;
- font-weight: 600;
- flex: 1;
- text-align: right
- }
- .btn-delete {
- width: 80rpx;
- height: 60rpx;
- min-width: 60rpx;
- min-height: 60rpx;
- display: inline-flex;
- align-items: center;
- justify-content: center;
- background: #fff0f0;
- color: #d9534f;
- border: 1rpx solid rgba(217,83,79,0.15);
- border-radius: 8rpx;
- margin-left: 30rpx
- }
- .fab {
- position: fixed;
- right: 28rpx;
- bottom: 160rpx;
- width: 110rpx;
- height: 110rpx;
- border-radius: 999px;
- background: linear-gradient(180deg, #ff7a00, #ff4a00);
- display: flex;
- align-items: center;
- justify-content: center;
- box-shadow: 0 6rpx 18rpx rgba(0, 0, 0, 0.2);
- z-index: 1200
- }
- .fab-inner {
- color: #fff;
- font-size: 56rpx;
- line-height: 56rpx
- }
- /* 模态框样式保持不变 */
- .modal {
- position: fixed;
- left: 0;
- right: 0;
- top: 0;
- bottom: 0;
- display: flex;
- align-items: flex-end;
- justify-content: center;
- z-index: 1300
- }
- .modal-backdrop {
- position: absolute;
- left: 0;
- right: 0;
- top: 0;
- bottom: 0;
- background: rgba(0, 0, 0, 0.4)
- }
- .modal-panel {
- position: relative;
- width: 100%;
- background: #fff;
- border-top-left-radius: 18rpx;
- border-top-right-radius: 18rpx;
- padding: 28rpx 24rpx 140rpx 24rpx;
- box-shadow: 0 -8rpx 30rpx rgba(0,0,0,0.12)
- }
- .modal-title {
- font-size: 56rpx;
- margin-block: 60rpx;
- color: #222;
- font-weight: 700;
- letter-spacing: 1rpx
- }
- .modal-inner {
- max-width: 70%;
- margin: 0 auto
- }
- .form-row {
- display: flex;
- align-items: center;
- justify-content: space-between;
- margin-bottom: 34rpx;
- padding: 14rpx 0;
- font-size: 32rpx
- }
- .input {
- width: 150rpx;
- text-align: right;
- padding: 16rpx;
- border-radius: 14rpx;
- border: 1rpx solid #eee;
- background: #fff7f0
- }
- .picker-display {
- color: #333
- }
- .btn-primary {
- background: #ff6a00;
- color: #fff;
- padding: 18rpx 22rpx;
- border-radius: 16rpx;
- text-align: center;
- width: 50%;
- box-shadow: 0 10rpx 28rpx rgba(255,106,0,0.18)
- }
- .drag-handle {
- width: 64rpx;
- height: 6rpx;
- background: rgba(0,0,0,0.08);
- border-radius: 999px;
- margin: 10rpx auto 14rpx auto
- }
- .modal-header {
- display: flex;
- align-items: center;
- justify-content: center;
- gap: 12rpx;
- margin-bottom: 6rpx
- }
- .label {
- color: #666
- }
- .ruler-wrap {
- margin: 12rpx 0
- }
- .fixed-footer {
- position: absolute;
- left: 0;
- right: 0;
- bottom: 40rpx;
- padding: 0 24rpx
- }
- .btn-full {
- width: 100%;
- padding: 18rpx;
- border-radius: 12rpx;
- }
- </style>
|