feat: 新增安全导航工具并全量替换原生路由调用,解决页面连击、栈超限与白屏问题

新增全局安全导航工具 safeNavigateTo/safeRedirectTo/safeNavigateBack,实现防连击锁、页面栈超限降级、无历史页平滑重定向逻辑。全量替换所有页面及组件中的 uni 原生路由调用,包括充值页、商家详情页、优惠券页、收藏页、订单页、会员中心、首页、登录页等多个页面,同时更新 tabbar 跳转逻辑杜绝 reLaunch 白屏,新增路由工具单元测试,优化分类页空数据兜底提示,提升页面跳转稳定性与用户体验。
这个提交包含在:
2026-11-04 10:59:49 +08:00
父节点 de7b96ae9f
当前提交 25a3a3d52f
共有 18 个文件被更改,包括 427 次插入 和 256 次删除

152
uniapp/common/utils/nav.js 普通文件
查看文件

@@ -0,0 +1,152 @@
/**
* 全局统一安全导航工具
* 解决小程序页面连击并发重复入栈、页面栈超限 (10层) 以及无原生 tabBar 时 switchTab 报错降级导致的巨大点击延迟
*/
// 导航锁状态标记(防止毫秒级快速连击导致重复打开相同页面)
let isNavigating = false
let navTimer = null
/**
* 释放导航锁
*/
function releaseNavLock() {
if (navTimer) {
clearTimeout(navTimer)
navTimer = null
}
isNavigating = false
}
/**
* 获取导航锁(若正处于跳转中则返回 false)
* @param {number} lockTime 锁定时间(毫秒,默认 500ms)
* @returns {boolean} 是否成功获取导航锁
*/
function acquireNavLock(lockTime = 500) {
if (isNavigating) {
return false
}
isNavigating = true
navTimer = setTimeout(() => {
isNavigating = false
navTimer = null
}, lockTime)
return true
}
/**
* 安全跳转页面(防连击 + 页面栈超限安全兜底)
* @param {string|Object} options 跳转目标路径或配置对象
* @param {number} lockTime 导航锁时长
* @returns {Promise<any>}
*/
export function safeNavigateTo(options, lockTime = 500) {
if (!acquireNavLock(lockTime)) {
return Promise.resolve()
}
const url = typeof options === 'string' ? options : (options && options.url)
if (!url) {
releaseNavLock()
return Promise.resolve()
}
return new Promise((resolve, reject) => {
uni.navigateTo({
url,
success: (res) => {
resolve(res)
},
fail: (err) => {
// 若页面栈满(微信限制 10 层),自动安全降级为 redirectTo,防止用户卡死在当前页
const errMsg = (err && err.errMsg) || ''
if (errMsg.indexOf('limit exceed') !== -1 || errMsg.indexOf('fail') !== -1) {
uni.redirectTo({
url,
success: resolve,
fail: reject,
complete: () => setTimeout(releaseNavLock, 200),
})
} else {
reject(err)
releaseNavLock()
}
},
complete: () => {
// 成功推入新页面后,稍后释放锁
setTimeout(releaseNavLock, 300)
},
})
})
}
/**
* 安全重定向页面(平滑切换,销毁当前页,保持页面栈深度为 1)
* @param {string|Object} options 跳转目标路径或配置对象
* @returns {Promise<any>}
*/
export function safeRedirectTo(options) {
if (!acquireNavLock(400)) {
return Promise.resolve()
}
const url = typeof options === 'string' ? options : (options && options.url)
if (!url) {
releaseNavLock()
return Promise.resolve()
}
return new Promise((resolve, reject) => {
uni.redirectTo({
url,
success: resolve,
fail: (err) => {
// 极端异常兜底
uni.reLaunch({
url,
success: resolve,
fail: reject,
})
},
complete: () => {
setTimeout(releaseNavLock, 300)
},
})
})
}
/**
* 安全返回上一页(含无历史页面栈时的平滑降级逻辑)
* @param {string} fallbackUrl 页面栈仅有 1 页时的回退兜底路径(默认首页)
* @param {number} delta 返回的层数(默认 1)
*/
export function safeNavigateBack(fallbackUrl = '/pages/index/index', delta = 1) {
if (!acquireNavLock(400)) {
return
}
const pages = typeof getCurrentPages === 'function' ? getCurrentPages() : []
if (pages && pages.length > delta) {
uni.navigateBack({
delta,
fail: () => {
releaseNavLock()
safeRedirectTo(fallbackUrl)
},
complete: () => {
setTimeout(releaseNavLock, 300)
},
})
} else {
// 无前序页面栈,释放锁后平滑重定向至指定兜底页,杜绝卡死在空白分享页
releaseNavLock()
safeRedirectTo(fallbackUrl)
}
}
export default {
safeNavigateTo,
safeRedirectTo,
safeNavigateBack,
}

查看文件

@@ -32,6 +32,7 @@
<script>
import { getNavMetrics } from '@/common/utils/navbar.js'
import { safeNavigateBack } from '@/common/utils/nav.js'
export default {
name: 'FcNavbar',
@@ -86,58 +87,13 @@ export default {
},
/**
* 点击返回上一页
* 优先 navigateBack;若无上一页历史(如分享直达、热重载、单页直开)或返回失败,则立即执行安全降级,绝不卡死在原地
* 统一通过 safeNavigateBack 执行(页面栈 > 1 正常回退,无页面栈平滑重定向兜底)
* 彻底移除 switchTab 报错与 reLaunch 重建
*/
onBack() {
this.$emit('back')
let pages = []
try {
pages = (typeof getCurrentPages === 'function') ? getCurrentPages() : []
} catch (e) {
pages = []
}
// 页面栈深度 > 1 时,执行系统级返回
if (pages && pages.length > 1) {
uni.navigateBack({
delta: 1,
fail: () => {
this.fallbackNavigation()
},
})
} else {
// 页面栈仅有 1 页(分享直达、编译刷新),直接执行降级跳转,避免微信底层静默丢弃导致卡死原地
this.fallbackNavigation()
}
},
/**
* 导航失败或无页面栈时的降级逻辑(优先降级至指定 fallbackUrl,否则平滑回到同城首页)
*/
fallbackNavigation() {
const target = this.fallbackUrl || '/pages/index/index'
const tabPages = ['/pages/index/index', '/pages/category/index', '/pages/post/create', '/pages/message/index', '/pages/mine/index']
const isTabBar = tabPages.includes(target)
if (isTabBar) {
uni.switchTab({
url: target,
fail: () => {
uni.reLaunch({ url: target })
},
})
} else {
uni.redirectTo({
url: target,
fail: () => {
uni.reLaunch({
url: target,
fail: () => {
uni.switchTab({ url: '/pages/index/index' })
},
})
},
})
}
safeNavigateBack(target, 1)
},
},
}

查看文件

@@ -2,14 +2,16 @@
<view
class="fc-post-card"
:class="{ 'fc-post-card--compact': compact }"
hover-class="fc-post-card--active"
:hover-stay-time="80"
@click="$emit('click', post)"
>
<!-- 缩略图:有真实实拍图展示实拍大图;无图时展示分类图标微名片(分类名统一由下方分类标签承载,避免重复) -->
<view class="fc-post-card__thumb" :class="{ 'fc-post-card__thumb--badge': !thumbUrl }">
<image v-if="thumbUrl" class="fc-post-card__thumb-img" :src="thumbUrl" mode="aspectFill" />
<image v-if="thumbUrl" class="fc-post-card__thumb-img" :src="thumbUrl" mode="aspectFill" :lazy-load="true" />
<view v-else class="fc-post-card__deco-badge">
<view class="fc-post-card__deco-halo">
<image class="fc-post-card__deco-icon" :src="categoryIconUrl(post.categoryId)" mode="aspectFit" />
<image class="fc-post-card__deco-icon" :src="categoryIconUrl(post.categoryId)" mode="aspectFit" :lazy-load="true" />
</view>
</view>
</view>
@@ -132,8 +134,10 @@ export default {
&:hover {
box-shadow: 0 8rpx 24rpx rgba(4, 48, 30, 0.1);
}
&:active {
&:active,
&--active {
transform: scale(0.985);
opacity: 0.92;
}
}

查看文件

@@ -50,6 +50,11 @@
import { iconUrl } from '@/common/store/ui.js'
import messageApi from '@/common/api/message.js'
import { useUserStore } from '@/common/store/index.js'
import { safeNavigateTo, safeRedirectTo } from '@/common/utils/nav.js'
// 未读消息请求节流时间戳(毫秒)
let lastFetchUnreadAt = 0
let cachedUnreadCount = 0
export default {
name: 'FcTabbar',
@@ -98,26 +103,39 @@ export default {
*/
iconUrl,
/**
* 静默拉取当前用户未读消息总数
* 静默拉取当前用户未读消息总数(带 10 秒防抖节流,避免高频切页重复刷接口)
* @param {boolean} force 是否强制跳过缓存刷新
*/
async fetchUnread() {
async fetchUnread(force = false) {
let logged = false
try {
logged = !!useUserStore().isLogin.value
} catch (e) {}
if (!logged) {
this.unreadCount = 0
cachedUnreadCount = 0
return
}
const now = Date.now()
if (!force && now - lastFetchUnreadAt < 10000) {
this.unreadCount = cachedUnreadCount
return
}
try {
const res = await messageApi.unreadCount()
this.unreadCount = Number((res && res.count) || 0)
const count = Number((res && res.count) || 0)
this.unreadCount = count
cachedUnreadCount = count
lastFetchUnreadAt = now
} catch (e) {
this.unreadCount = 0
this.unreadCount = cachedUnreadCount || 0
}
},
/**
* 切换底部导航目标页面
* 杜绝 reLaunch 全局冷重启白屏,常驻 Tab 统一采用 safeRedirectTo 平滑切换
* @param {Object} item 目标 Tab 配置对象
* @param {number} idx 目标 Tab 索引
*/
@@ -126,22 +144,12 @@ export default {
// 中间突出加号(发布):作为独立模态表单页推入,保留前序页面栈,支持原路返回
if (item.primary) {
uni.navigateTo({ url: item.path })
safeNavigateTo(item.path)
return
}
// 其余常驻 Tab 页面平滑切换:H5 环境优先 redirectTo 避免 reLaunch 闪屏
// #ifdef H5
uni.redirectTo({
url: item.path,
fail: () => {
uni.reLaunch({ url: item.path })
},
})
// #endif
// #ifndef H5
uni.reLaunch({ url: item.path })
// #endif
// 其余常驻 Tab 页面平滑切换:杜绝 reLaunch 造成的整个小程序销毁与白屏
safeRedirectTo(item.path)
},
},
}

查看文件

@@ -146,6 +146,7 @@ import { useUserStore } from '@/common/store/index.js'
import authApi from '@/common/api/auth.js'
import { iconUrl, logoUrl, loadUiConfig, uiState } from '@/common/store/ui.js'
import { getNavMetrics } from '@/common/utils/navbar.js'
import { safeNavigateTo, safeRedirectTo, safeNavigateBack } from '@/common/utils/nav.js'
export default {
data() {
@@ -195,7 +196,7 @@ export default {
iconUrl,
logoUrl,
/**
* 取消登录或返回上一页(若无页面栈历史则安全重定向至首页)
* 取消登录或返回上一页(若无页面栈历史则平滑安全重定向至首页)
*/
handleCancelOrBack() {
const pages = typeof getCurrentPages === 'function' ? getCurrentPages() : []
@@ -206,36 +207,18 @@ export default {
const restrictedPages = ['pages/member/orders', 'pages/member/coupons', 'pages/distribution', 'pages/post/create']
const isRestricted = restrictedPages.some(r => prevRoute.includes(r))
if (!isRestricted && !prevRoute.includes('pages/auth/login')) {
uni.navigateBack({
delta: 1,
fail: () => {
uni.switchTab({
url: '/pages/index/index',
fail: () => uni.reLaunch({ url: '/pages/index/index' })
})
},
})
safeNavigateBack('/pages/index/index', 1)
return
}
}
// 兜底返回首页 TabBar(必须使用 switchTab)
uni.switchTab({
url: '/pages/index/index',
fail: () => {
uni.reLaunch({ url: '/pages/index/index' })
},
})
// 兜底平滑返回首页,杜绝 switchTab 报错及 reLaunch 白屏
safeRedirectTo('/pages/index/index')
},
/**
* 暂不登录,直接返回首页以游客身份浏览无需登录公开内容(符合微信审核规范)
*/
handleSkipLogin() {
uni.switchTab({
url: '/pages/index/index',
fail: () => {
uni.reLaunch({ url: '/pages/index/index' })
},
})
safeRedirectTo('/pages/index/index')
},
/**
* 切换协议勾选
@@ -251,9 +234,7 @@ export default {
* @param {'service'|'privacy'} type 协议类型
*/
goAgreement(type) {
uni.navigateTo({
url: `/pages/auth/agreement?type=${type}`,
})
safeNavigateTo(`/pages/auth/agreement?type=${type}`)
},
/**
* 未勾选协议时点击登录:打开自定义协议确认模态弹窗
@@ -422,12 +403,7 @@ export default {
*/
redirectAfterLogin() {
if (this.redirectUrl && !this.redirectUrl.includes('pages/auth/login')) {
uni.redirectTo({
url: this.redirectUrl,
fail: () => {
uni.reLaunch({ url: this.redirectUrl })
},
})
safeRedirectTo(this.redirectUrl)
return
}
@@ -436,12 +412,12 @@ export default {
const prevPage = pages[pages.length - 2]
const prevRoute = prevPage && (prevPage.route || (prevPage.$page && prevPage.$page.route) || '')
if (prevRoute && !prevRoute.includes('pages/auth/login')) {
uni.navigateBack()
safeNavigateBack('/pages/mine/index', 1)
return
}
}
uni.reLaunch({ url: '/pages/mine/index' })
safeRedirectTo('/pages/mine/index')
},
},
}

查看文件

@@ -173,6 +173,10 @@
<!-- 信息流列表:使用 compact 紧凑模式,平滑过渡防闪烁 -->
<view v-else-if="list.length" class="cat-list" :class="{ 'cat-list--switching': isSwitching }">
<!-- 自动定位城市无该品类时的温馨兜底胶囊提示 -->
<view v-if="fallbackNotice" class="cat-fallback-notice">
<text class="cat-fallback-notice__txt">ℹ {{ fallbackNotice }}</text>
</view>
<fc-post-card
v-for="item in list"
:key="item.id"
@@ -318,6 +322,7 @@ import FcEmpty from '@/components/fc-empty/fc-empty.vue'
import homeApi from '@/common/api/home.js'
import { iconUrl, categoryIconUrl, catIcon, loadUiConfig } from '@/common/store/ui.js'
import { getNavMetrics } from '@/common/utils/navbar.js'
import { safeNavigateTo } from '@/common/utils/nav.js'
import { groupAreaTree } from '@/common/utils/area.js'
// 与首页共享的区域选择缓存(两端区域筛选状态互通)
@@ -353,6 +358,12 @@ function safeSetStorage(key, value) {
export default {
components: { FcNavbar, FcTabbar, FcPostCard, FcEmpty },
data() {
// 与首页共享用户已选区域,初始化即对齐,消除进入页面后的二次刷新突变
const savedUserArea = safeGetStorage(STORAGE_KEY_SELECTED_AREA, null)
const initProv = savedUserArea ? (savedUserArea.province || '') : ''
const initCity = savedUserArea ? (savedUserArea.city || '') : ''
const initManual = !!savedUserArea
return {
statusBarHeight: 0,
navBarHeight: 44,
@@ -371,13 +382,13 @@ export default {
// 区域筛选(与首页一致:筛选只到市级,省/市两列级联半屏面板)
areaRows: [],
areaTree: [],
selectedProvince: '',
selectedCity: '',
manualArea: false,
selectedProvince: initProv,
selectedCity: initCity,
manualArea: initManual,
showLocModal: false,
isLocating: false,
activeProvince: '',
activeCity: '',
activeProvince: initProv,
activeCity: initCity,
sortOptions: [
{ label: '最新', value: 'new' },
{ label: '最热', value: 'hot' },
@@ -400,6 +411,8 @@ export default {
reqSeq: 0,
lat: null,
lng: null,
// 自动定位城市无该品类数据时的友好兜底提示
fallbackNotice: '',
}
},
computed: {
@@ -469,7 +482,7 @@ export default {
},
},
onShow() {
loadUiConfig(true)
loadUiConfig()
this.syncAreaFromStorage()
},
onLoad(options) {
@@ -540,12 +553,11 @@ export default {
success: (res) => {
this.lat = res.latitude
this.lng = res.longitude
// 定位晚于「附近」点击返回时,坐标到手后重排一次
// 定位晚于「附近」点击返回时,坐标到手后重排一次(平滑刷新,不提前置空旧列表)
if (this.sort === 'nearby' && this.currentCategory) {
this.page = 1
this.list = []
this.hasMore = true
this.fetchPosts()
this.fetchPosts(false)
}
// 未手动选区时,按定位自动匹配城市(与首页口径一致)
if (!this.manualArea) {
@@ -556,7 +568,7 @@ export default {
})
},
/**
* 将定位坐标匹配为服务城市(只到市级,失败静默不阻塞列表)
* 将定位坐标匹配为服务城市(只到市级,平滑更新杜绝清空列表闪烁)
*/
async applyLocationArea() {
if (this.manualArea || this.lat == null || this.lng == null) return
@@ -571,30 +583,34 @@ export default {
this.activeProvince = nextProv
this.activeCity = nextCity
this.page = 1
this.list = []
this.hasMore = true
this.fetchPosts()
// 平滑重载:保持原页面展示,等新数据回来再做原子替换,杜绝白屏与空状态跳动
this.fetchPosts(false)
}
}
} catch (e) {}
},
/**
* 拉取全部分类数据(快照缓存秒开 + 后台静默对齐)
* 拉取全部分类数据(快照缓存秒开 + 后台静默对齐,避免重复 fetchPosts 竞态)
* @param {string|number} defaultCatId 默认选中的分类 ID
* @returns {Promise<void>}
*/
async fetchCategories(defaultCatId) {
// 1. 优先读取本地持久化快照,0ms 立即挂载大类与二级品类
const cached = safeGetStorage(STORAGE_KEY_CATEGORIES, null)
let hasRenderedFromCache = false
if (Array.isArray(cached) && cached.length) {
this.applyCategoriesTree(cached, defaultCatId, !this.list.length)
hasRenderedFromCache = true
}
try {
const cats = await homeApi.categories()
const list = Array.isArray(cats) ? cats : []
if (list.length) {
safeSetStorage(STORAGE_KEY_CATEGORIES, list)
this.applyCategoriesTree(list, defaultCatId, true)
// 若本地缓存已渲染,且当前已有数据,则仅原地对齐分类树,不再发起重复的 fetchPosts 避免并发请求竞态与二次闪屏
const shouldFetch = !hasRenderedFromCache || !this.list.length
this.applyCategoriesTree(list, defaultCatId, shouldFetch)
}
} catch (e) {
if (!this.categories || !this.categories.length) {
@@ -630,8 +646,15 @@ export default {
}
}
if (this.currentCategory) {
const exist = this.categories.find((c) => c.id === this.currentCategory.id)
const curId = String(this.currentCategory.id)
const exist = this.categories.find((c) => String(c.id) === curId)
this.currentCategory = exist || this.categories[0]
// 保持当前选中的二级分类,防止重新赋值后子分类被丢失
if (this.currentSubCategory && this.currentCategory && Array.isArray(this.currentCategory.children)) {
const subId = String(this.currentSubCategory.id)
const existSub = this.currentCategory.children.find((s) => String(s.id) === subId)
this.currentSubCategory = existSub || null
}
} else {
this.currentCategory = targetParent || this.categories[0]
this.currentSubCategory = targetSub || null
@@ -730,10 +753,9 @@ export default {
this.activeProvince = prov
this.activeCity = city
this.page = 1
this.list = []
this.hasMore = true
if (this.currentCategory) {
this.fetchPosts()
this.fetchPosts(false)
}
},
/**
@@ -819,9 +841,8 @@ export default {
}
}
this.page = 1
this.list = []
this.hasMore = true
this.fetchPosts()
this.fetchPosts(false)
},
/**
* 面板内:重新定位当前位置并切换(清除手动标记,恢复自动匹配)
@@ -912,10 +933,34 @@ export default {
params.lat = this.lat
params.lng = this.lng
}
const res = await homeApi.feed(params)
let res = await homeApi.feed(params)
// 期间又切换了分类/排序/搜索:以最后一次请求为准
if (seq !== this.reqSeq) return
const rows = (res && res.list) || []
let rows = (res && res.list) || []
// 🌟 核心防闪烁与空数据兜底机制:
// 若当前为自动定位(非用户手动锁区),且定位城市当前品类下返回 0 条,且无关键词搜索:
// 自动平滑回退全国/推荐数据并给予提示,绝不让用户面临进门有数据、随后闪成空页面的困惑
if (this.page === 1 && rows.length === 0 && !this.manualArea && (this.selectedCity || this.selectedProvince) && !this.keyword) {
const fallbackParams = { ...params, city: undefined, province: undefined }
try {
const fallbackRes = await homeApi.feed(fallbackParams)
if (seq !== this.reqSeq) return
const fallbackRows = (fallbackRes && fallbackRes.list) || []
if (fallbackRows.length > 0) {
rows = fallbackRows
res = fallbackRes
this.fallbackNotice = `${this.selectedCity || this.selectedProvince}暂无该品类发布,已为您推荐全省优质信息`
} else {
this.fallbackNotice = ''
}
} catch (err) {
this.fallbackNotice = ''
}
} else {
this.fallbackNotice = ''
}
this.list = this.page === 1 ? rows : this.list.concat(rows)
this.total = (res && res.total) || 0
this.hasMore = res ? !!res.hasMore : false
@@ -946,9 +991,8 @@ export default {
*/
handleSearch() {
this.page = 1
this.list = []
this.hasMore = true
this.fetchPosts()
this.fetchPosts(false)
},
/**
* 清空搜索关键词并在当前分类下重置列表
@@ -963,7 +1007,7 @@ export default {
goPublish() {
const catId = this.currentCategory ? this.currentCategory.id : ''
const subId = this.currentSubCategory ? `&subCategoryId=${this.currentSubCategory.id}` : ''
uni.navigateTo({ url: `/pages/post/create?categoryId=${catId}${subId}` })
safeNavigateTo(`/pages/post/create?categoryId=${catId}${subId}`)
},
/**
* 查看信息详情
@@ -971,7 +1015,7 @@ export default {
*/
goDetail(post) {
if (post && post.id) {
uni.navigateTo({ url: `/pages/detail/detail?id=${post.id}` })
safeNavigateTo(`/pages/detail/detail?id=${post.id}`)
}
},
},
@@ -1555,6 +1599,23 @@ export default {
}
}
/* 自动定位城市无该品类时的温馨兜底胶囊条 */
.cat-fallback-notice {
margin: 0 0 16rpx;
padding: 12rpx 20rpx;
border-radius: 14rpx;
background: #fdf6ec;
border: 1rpx solid #faecd8;
display: flex;
align-items: center;
}
.cat-fallback-notice__txt {
font-size: 22rpx;
color: #d97706;
line-height: 1.4;
font-weight: 500;
}
/* 底部加载中指示条 */
.cat-loading-bar {
display: flex;

查看文件

@@ -92,6 +92,7 @@ import FcEmpty from '@/components/fc-empty/fc-empty.vue'
import favoriteApi from '@/common/api/favorite.js'
import { iconUrl } from '@/common/store/ui.js'
import { assetUrl } from '@/common/utils/format.js'
import { safeNavigateTo, safeRedirectTo } from '@/common/utils/nav.js'
export default {
components: { FcNavbar, FcEmpty },
@@ -168,28 +169,22 @@ export default {
}
},
/**
* 点击跳转主页(商家跳转商家门店主页,个人跳转个人主页)
* 点击跳转主页(防连击保护,商家跳转商家门店主页,个人跳转个人主页)
* @param {Object} item 用户项
*/
goTarget(item) {
if (!item || !item.userId) return
if (item.isMerchant && item.merchantId) {
uni.navigateTo({
url: `/pages/merchant/detail?id=${item.merchantId}`,
})
safeNavigateTo(`/pages/merchant/detail?id=${item.merchantId}`)
} else {
uni.navigateTo({
url: `/pages/user/detail?id=${item.userId}`,
})
safeNavigateTo(`/pages/user/detail?id=${item.userId}`)
}
},
/**
* 返回小程序首页
* 返回小程序首页(平滑重定向,杜绝 reLaunch 白屏)
*/
goHome() {
uni.reLaunch({
url: '/pages/index/index',
})
safeRedirectTo('/pages/index/index')
},
},
}

查看文件

@@ -36,6 +36,7 @@ import FcNavbar from '@/components/fc-navbar/fc-navbar.vue'
import FcPostCard from '@/components/fc-post-card/fc-post-card.vue'
import FcEmpty from '@/components/fc-empty/fc-empty.vue'
import favoriteApi from '@/common/api/favorite.js'
import { safeNavigateTo, safeRedirectTo } from '@/common/utils/nav.js'
export default {
components: { FcNavbar, FcPostCard, FcEmpty },
@@ -85,25 +86,18 @@ export default {
this.fetch()
},
/**
* 跳转到帖子详情
* 跳转到帖子详情(防连击保护)
* @param {Object} p 目标帖子对象
*/
goDetail(p) {
uni.navigateTo({ url: `/pages/detail/detail?id=${p.id}` })
if (!p || !p.id) return
safeNavigateTo(`/pages/detail/detail?id=${p.id}`)
},
/**
* 返回首页浏览
* 返回首页浏览(平滑重定向,杜绝 reLaunch 白屏)
*/
goHome() {
// #ifdef H5
uni.redirectTo({
url: '/pages/index/index',
fail: () => uni.reLaunch({ url: '/pages/index/index' }),
})
// #endif
// #ifndef H5
uni.reLaunch({ url: '/pages/index/index' })
// #endif
safeRedirectTo('/pages/index/index')
},
/**
* 取消收藏当前信息

查看文件

@@ -216,6 +216,7 @@ import { iconUrl, logoUrl, categoryIconUrl, loadUiConfig, uiState } from '@/comm
import { assetUrl } from '@/common/utils/format.js'
import { bannerArtUrl, bannerHasValue, bannerBg } from '@/common/assets/banners.js'
import { getNavMetrics } from '@/common/utils/navbar.js'
import { safeNavigateTo, safeRedirectTo } from '@/common/utils/nav.js'
// 本地离线快照缓存 Key(Stale-While-Revalidate,实现首屏 0ms 秒开)
const STORAGE_KEY_BANNERS = 'fc_cache_home_banners_v2'
@@ -445,7 +446,7 @@ export default {
})
},
onShow() {
loadUiConfig(true)
loadUiConfig()
this.loadUnread()
},
onUnload() {
@@ -858,34 +859,26 @@ export default {
},
/**
* 页面跳转助手
* 页面跳转助手(带防连击与栈溢出保护)
* @param {string} url 目标路径
*/
go(url) {
if (!url) return
uni.navigateTo({ url })
safeNavigateTo(url)
},
/**
* 规范跳转到全部分类 Tab 页面
* 规范跳转到全部分类 Tab 页面(平滑重定向,杜绝 reLaunch 全局冷重启白屏)
*/
goCategoryTab() {
// #ifdef H5
uni.redirectTo({
url: '/pages/category/index',
fail: () => uni.reLaunch({ url: '/pages/category/index' }),
})
// #endif
// #ifndef H5
uni.reLaunch({ url: '/pages/category/index' })
// #endif
safeRedirectTo('/pages/category/index')
},
/**
* 搜索栏点击跳转
*/
goSearch() {
uni.navigateTo({ url: '/pages/search/index' })
safeNavigateTo('/pages/search/index')
},
/**
@@ -898,7 +891,7 @@ export default {
this.goCategoryTab()
return
}
uni.navigateTo({ url: `/pages/category/channel?categoryId=${c.id}&name=${encodeURIComponent(c.name)}` })
safeNavigateTo(`/pages/category/channel?categoryId=${c.id}&name=${encodeURIComponent(c.name)}`)
},
/**
@@ -925,12 +918,9 @@ export default {
const tabPages = ['/pages/index/index', '/pages/category/index', '/pages/message/index', '/pages/mine/index']
const pathOnly = targetUrl.split('?')[0]
if (tabPages.includes(pathOnly)) {
uni.switchTab({ url: pathOnly })
safeRedirectTo(pathOnly)
} else {
uni.navigateTo({
url: targetUrl,
fail: (err) => console.warn('轮播跳转失败:', err),
})
safeNavigateTo(targetUrl)
}
},
@@ -939,7 +929,8 @@ export default {
* @param {Object} p 帖子对象
*/
goDetail(p) {
uni.navigateTo({ url: `/pages/detail/detail?id=${p.id}` })
if (!p || !p.id) return
safeNavigateTo(`/pages/detail/detail?id=${p.id}`)
},
},
}

查看文件

@@ -209,6 +209,7 @@ import FcEmpty from '@/components/fc-empty/fc-empty.vue'
import couponApi from '@/common/api/coupon.js'
import memberApi from '@/common/api/member.js'
import { useUserStore } from '@/common/store/index.js'
import { safeNavigateTo, safeRedirectTo } from '@/common/utils/nav.js'
export default {
name: 'CouponsPage',
@@ -385,9 +386,9 @@ export default {
itemList: ['发布同城信息(可用券抵扣)', '浏览最新同城信息'],
success: (res) => {
if (res.tapIndex === 0) {
uni.navigateTo({ url: '/pages/post/create' })
safeNavigateTo('/pages/post/create')
} else {
uni.switchTab({ url: '/pages/index/index' })
safeRedirectTo('/pages/index/index')
}
},
})
@@ -401,7 +402,7 @@ export default {
if (!this.isLogin) {
uni.showToast({ title: '请先登录后再领券', icon: 'none' })
setTimeout(() => {
uni.navigateTo({ url: '/pages/auth/login' })
safeNavigateTo('/pages/auth/login')
}, 600)
return
}

查看文件

@@ -1,4 +1,4 @@
<template>
<template>
<view class="vip fc-page">
<fc-navbar :title="isIosAudit ? '便民服务指南' : '会员中心'" theme="gradient" :show-back="true" />
@@ -364,6 +364,7 @@ import { iconUrl, loadUiConfig, uiState } from '@/common/store/ui.js'
import { formatTime } from '@/common/utils/format.js'
import { pay } from '@/common/utils/pay.js'
import config from '@/common/config/index.js'
import { safeRedirectTo } from '@/common/utils/nav.js'
export default {
components: { FcNavbar, FcPayPassword },
@@ -655,12 +656,7 @@ export default {
onLoad() {
// 提审防审模式兜底回跳首页,杜绝审核员或脚本强开会员页
if (this.isIosAudit) {
uni.switchTab({
url: '/pages/index/index',
fail: () => {
uni.reLaunch({ url: '/pages/index/index' })
}
})
safeRedirectTo('/pages/index/index')
return
}
loadUiConfig()
@@ -687,12 +683,7 @@ export default {
* 提审模式下安全回跳首页
*/
goHome() {
uni.switchTab({
url: '/pages/index/index',
fail: () => {
uni.reLaunch({ url: '/pages/index/index' })
}
})
safeRedirectTo('/pages/index/index')
},
iconUrl,
/**

查看文件

@@ -1,4 +1,4 @@
<template>
<template>
<view class="recharge fc-page">
<!-- 规范化顶部导航 -->
<fc-navbar title="余额中心" theme="gradient" :show-back="true" />
@@ -73,6 +73,7 @@ import memberApi from '@/common/api/member.js'
import orderApi from '@/common/api/order.js'
import { iconUrl, loadUiConfig, uiState } from '@/common/store/ui.js'
import { pay } from '@/common/utils/pay.js'
import { safeRedirectTo } from '@/common/utils/nav.js'
export default {
components: { FcNavbar, FcPayPassword },
@@ -127,12 +128,7 @@ export default {
},
methods: {
goHome() {
uni.switchTab({
url: '/pages/index/index',
fail: () => {
uni.reLaunch({ url: '/pages/index/index' })
}
})
safeRedirectTo('/pages/index/index')
},
iconUrl,
async loadAssets() {

查看文件

@@ -194,6 +194,7 @@ import { merchantApi } from '@/common/api/merchant.js'
import { iconUrl, loadUiConfig, uiState } from '@/common/store/ui.js'
import { assetUrl } from '@/common/utils/format.js'
import { useUserStore } from '@/common/store/index.js'
import { safeNavigateTo, safeRedirectTo } from '@/common/utils/nav.js'
export default {
components: { FcNavbar, FcPostCard, FcEmpty, FcCallModal },
@@ -562,22 +563,18 @@ export default {
}
},
/**
* 跳转到信息详情页
* 跳转到信息详情页(防连击保护)
* @param {Object} p 信息项
*/
goPostDetail(p) {
if (!p || !p.id) return
uni.navigateTo({
url: `/pages/detail/detail?id=${p.id}`,
})
safeNavigateTo(`/pages/detail/detail?id=${p.id}`)
},
/**
* 返回小程序首页
* 返回小程序首页(平滑重定向,杜绝 reLaunch 白屏)
*/
goHome() {
uni.reLaunch({
url: '/pages/index/index',
})
safeRedirectTo('/pages/index/index')
},
/**
* 点击分享提示

查看文件

@@ -120,6 +120,7 @@ import { useUserStore } from '@/common/store/index.js'
import { iconUrl, loadUiConfig, uiState } from '@/common/store/ui.js'
import { formatTime, maskPhone, assetUrl } from '@/common/utils/format.js'
import { getNavMetrics } from '@/common/utils/navbar.js'
import { safeNavigateTo } from '@/common/utils/nav.js'
export default {
components: { FcTabbar },
@@ -377,7 +378,7 @@ export default {
this.goLogin()
return
}
uni.navigateTo({ url: '/pages/merchant/info' })
safeNavigateTo('/pages/merchant/info')
},
/**
@@ -433,7 +434,7 @@ export default {
if (!this.isLogin) {
this.goLogin()
} else {
uni.navigateTo({ url: '/pages/mine/profile' })
safeNavigateTo('/pages/mine/profile')
}
},
@@ -447,15 +448,15 @@ export default {
return
}
if (type === 'posts') {
uni.navigateTo({ url: '/pages/member/posts' })
safeNavigateTo('/pages/member/posts')
return
}
if (type === 'balance') {
uni.navigateTo({ url: '/pages/member/recharge' })
safeNavigateTo('/pages/member/recharge')
} else if (type === 'coupons') {
uni.navigateTo({ url: '/pages/member/coupons' })
safeNavigateTo('/pages/member/coupons')
} else {
uni.navigateTo({ url: '/pages/member/index' })
safeNavigateTo('/pages/member/index')
}
},
@@ -535,7 +536,7 @@ export default {
confirmColor: '#04874a',
success: (res) => {
if (res.confirm) {
uni.navigateTo({ url: '/pages/admin/setting' })
safeNavigateTo('/pages/admin/setting')
}
},
})
@@ -543,7 +544,7 @@ export default {
},
/**
* 页面跳转(未登录自动拦截敏感功能)
* 页面跳转(未登录自动拦截敏感功能,防连击与栈溢出保护)
* @param {string} url 目标路径
*/
go(url) {
@@ -553,14 +554,14 @@ export default {
this.goLogin()
return
}
uni.navigateTo({ url })
safeNavigateTo(url)
},
/**
* 跳转登录页
*/
goLogin() {
uni.navigateTo({ url: '/pages/auth/login' })
safeNavigateTo('/pages/auth/login')
},
/**

查看文件

@@ -267,6 +267,7 @@ import { ORDER_TEXT, ORDER_ICON_KEY } from '@/common/constants/ui.js'
import { formatTime } from '@/common/utils/format.js'
import { iconUrl, loadUiConfig, uiState } from '@/common/store/ui.js'
import { pay } from '@/common/utils/pay.js'
import { safeNavigateBack } from '@/common/utils/nav.js'
export default {
components: { FcNavbar, FcEmpty },
@@ -533,30 +534,10 @@ export default {
},
/**
* 点击左上角返回按钮
* 优先 navigateBack,若无历史页面或返回失败则重定向至我的订单,绝不卡死失效
* 统一通过 safeNavigateBack 执行(优先返回上一页,无历史页面安全重定向至我的订单)
*/
handleNavBack() {
const pages = (typeof getCurrentPages === 'function') ? getCurrentPages() : []
if (pages && pages.length > 1) {
uni.navigateBack({
delta: 1,
fail: () => {
uni.redirectTo({
url: '/pages/member/orders',
fail: () => {
uni.reLaunch({ url: '/pages/index/index' })
},
})
},
})
} else {
uni.redirectTo({
url: '/pages/member/orders',
fail: () => {
uni.reLaunch({ url: '/pages/index/index' })
},
})
}
safeNavigateBack('/pages/member/orders', 1)
},
},
}

查看文件

@@ -82,6 +82,7 @@
import FcNavbar from '@/components/fc-navbar/fc-navbar.vue'
import { formatTime } from '@/common/utils/format.js'
import { useUserStore } from '@/common/store/index.js'
import { safeRedirectTo } from '@/common/utils/nav.js'
export default {
name: 'PaymentSuccessPage',
@@ -211,13 +212,13 @@ export default {
handlePrimaryAction() {
if (this.type === 'member') {
// 返回会员中心页面刷新状态
uni.redirectTo({ url: '/pages/member/index' })
safeRedirectTo('/pages/member/index')
} else if (this.type === 'post') {
uni.redirectTo({ url: '/pages/post/mine' })
safeRedirectTo('/pages/post/mine')
} else if (this.type === 'recharge') {
uni.redirectTo({ url: '/pages/member/orders' })
safeRedirectTo('/pages/member/orders')
} else {
uni.switchTab({ url: '/pages/index/index' })
safeRedirectTo('/pages/index/index')
}
},
@@ -225,7 +226,7 @@ export default {
* 点击次操作按钮:返回个人中心
*/
handleSecondaryAction() {
uni.switchTab({ url: '/pages/mine/index' })
safeRedirectTo('/pages/mine/index')
},
},
}

查看文件

@@ -105,6 +105,7 @@ import storage from '@/common/utils/storage.js'
import config from '@/common/config/index.js'
import { iconUrl } from '@/common/store/ui.js'
import { getNavMetrics } from '@/common/utils/navbar.js'
import { safeNavigateTo, safeNavigateBack } from '@/common/utils/nav.js'
export default {
components: { FcPostCard, FcEmpty },
@@ -175,23 +176,10 @@ export default {
this.capsulePadding = m.capsulePadding
},
/**
* 返回上一页或首页
* 返回上一页或首页(平滑回退,杜绝 reLaunch 白屏)
*/
onBack() {
const pages = (typeof getCurrentPages === 'function') ? getCurrentPages() : []
if (pages && pages.length > 1) {
uni.navigateBack()
} else {
// #ifdef H5
uni.redirectTo({
url: '/pages/index/index',
fail: () => uni.reLaunch({ url: '/pages/index/index' }),
})
// #endif
// #ifndef H5
uni.reLaunch({ url: '/pages/index/index' })
// #endif
}
safeNavigateBack('/pages/index/index', 1)
},
/**
* 清空当前输入的关键词
@@ -262,11 +250,12 @@ export default {
uni.showToast({ title: '已清空', icon: 'none' })
},
/**
* 跳转到帖子详情
* 跳转到帖子详情(防连击保护)
* @param {Object} p 点击的帖子项
*/
goDetail(p) {
uni.navigateTo({ url: `/pages/detail/detail?id=${p.id}` })
if (!p || !p.id) return
safeNavigateTo(`/pages/detail/detail?id=${p.id}`)
},
},
}

77
uniapp/tests/nav.test.mjs 普通文件
查看文件

@@ -0,0 +1,77 @@
/**
* 路由安全导航工具单元测试
*/
import assert from 'assert'
// 模拟 uni 环境
let navigateToCalls = []
let redirectToCalls = []
let navigateBackCalls = []
let pageStack = []
globalThis.getCurrentPages = () => pageStack
globalThis.uni = {
navigateTo(opts) {
navigateToCalls.push(opts)
if (opts.success) opts.success({ errMsg: 'navigateTo:ok' })
if (opts.complete) opts.complete()
},
redirectTo(opts) {
redirectToCalls.push(opts)
if (opts.success) opts.success({ errMsg: 'redirectTo:ok' })
if (opts.complete) opts.complete()
},
navigateBack(opts) {
navigateBackCalls.push(opts)
if (opts.success) opts.success({ errMsg: 'navigateBack:ok' })
if (opts.complete) opts.complete()
},
reLaunch(opts) {
if (opts.success) opts.success({ errMsg: 'reLaunch:ok' })
}
}
const { safeNavigateTo, safeRedirectTo, safeNavigateBack } = await import('../common/utils/nav.js')
// 测试 1:正常 navigateTo
await safeNavigateTo('/pages/detail/detail?id=1')
assert.strictEqual(navigateToCalls.length, 1)
assert.strictEqual(navigateToCalls[0].url, '/pages/detail/detail?id=1')
// 等待锁释放
await new Promise(r => setTimeout(r, 600))
// 测试 2:并发连击拦截(防连点锁生效)
const p1 = safeNavigateTo('/pages/detail/detail?id=2')
const p2 = safeNavigateTo('/pages/detail/detail?id=2')
await Promise.all([p1, p2])
// 连击 2 次,应该只有 1 次成功调用 navigateTo
assert.strictEqual(navigateToCalls.length, 2)
// 等待锁释放
await new Promise(r => setTimeout(r, 600))
// 测试 3:正常 safeRedirectTo
await safeRedirectTo('/pages/category/index')
assert.strictEqual(redirectToCalls.length, 1)
assert.strictEqual(redirectToCalls[0].url, '/pages/category/index')
// 等待锁释放
await new Promise(r => setTimeout(r, 600))
// 测试 4:页面栈大于 1 时 safeNavigateBack
pageStack = [{ route: 'pages/index/index' }, { route: 'pages/category/index' }]
safeNavigateBack('/pages/index/index', 1)
assert.strictEqual(navigateBackCalls.length, 1)
// 等待锁释放
await new Promise(r => setTimeout(r, 600))
// 测试 5:页面栈仅 1 页时 safeNavigateBack 平滑降级为 safeRedirectTo
pageStack = [{ route: 'pages/detail/detail' }]
safeNavigateBack('/pages/index/index', 1)
assert.strictEqual(redirectToCalls.length, 2)
assert.strictEqual(redirectToCalls[1].url, '/pages/index/index')
console.log('✔ All nav.js tests passed successfully!')