Files
zt-closet-wxmini-frontend/miniprogram/components/navigation-bar/navigation-bar.ts
T
2026-09-15 16:01:59 +08:00

89 lines
2.9 KiB
TypeScript

import { logger } from '../../utils/logger'
// 日志模块名
const LOG = 'navigation-bar'
Component({
options: {
multipleSlots: true, // 右侧操作槽(如「编辑」「取消」「更多」)
},
properties: {
// 滚动收缩后显示的居中标题
title: {
type: String,
value: '',
},
// 是否显示返回按钮
back: {
type: Boolean,
value: true,
},
// 返回的页面深度
delta: {
type: Number,
value: 1,
},
// 是否已滚动(由页面 utils/nav.ts 的 handler 驱动)
scrolled: {
type: Boolean,
value: false,
},
},
data: {
// 状态栏高度(px)与微信胶囊占位(右侧 padding)
safeTop: 0,
capsulePad: '',
},
lifetimes: {
attached() {
const rect = wx.getMenuButtonBoundingClientRect()
const apply = (windowWidth: number, safeTop: number) => {
this.setData({
safeTop: safeTop > 0 ? safeTop : 0,
// 预留右上角胶囊宽度,保证右侧操作不压到胶囊
capsulePad: `padding-right: ${Math.max(windowWidth - rect.left, 0)}px;`,
})
}
// wx.getSystemInfo 已废弃(基础库 2.20.1+ 拆分接口),改用同步的 window/device 接口
const wxAny = wx as any
if (typeof wxAny.getWindowInfo === 'function') {
const win = wxAny.getWindowInfo()
const dev = typeof wxAny.getDeviceInfo === 'function' ? wxAny.getDeviceInfo() : {}
apply(win.windowWidth, win.safeArea ? win.safeArea.top : 0)
logger.debug(LOG, '布局计算完成, 窗口宽=', win.windowWidth, '平台=', dev.platform || win.platform)
return
}
// 低版本基础库走废弃接口兜底
logger.warn(LOG, 'getWindowInfo 不可用,降级到已废弃的 wx.getSystemInfo')
wx.getSystemInfo({
success: (res) => apply(res.windowWidth, res.safeArea ? res.safeArea.top : 0),
})
},
},
methods: {
back() {
const data = this.data
if (data.delta) {
// 从分享卡片等场景直接打开时页面栈仅一层,navigateBack 无上一页可退,
// 此时兜底 switchTab 回衣橱,避免点击返回毫无反应。
const pages = typeof getCurrentPages === 'function' ? getCurrentPages() : []
if (pages.length > data.delta) {
logger.debug(LOG, '返回上一页, delta=', data.delta)
wx.navigateBack({
delta: data.delta,
fail: (e) => logger.warn(LOG, 'navigateBack 失败, err=', e && e.errMsg),
})
} else {
logger.warn(LOG, '页面栈不足,switchTab 回衣橱兜底, 栈深=', pages.length)
wx.switchTab({
url: '/pages/wardrobe/wardrobe',
fail: (e) => logger.warn(LOG, 'switchTab 衣橱失败, err=', e && e.errMsg),
})
}
}
this.triggerEvent('back', { delta: data.delta }, {})
},
},
})