| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758 |
- /**
- * 路由登录拦截器(黑名单模式)
- * 适用:大部分页面可访问,少数页面需要登录
- */
- import { userToken } from "@/composables/config";
- import {
- needLoginPages as _needLoginPages,
- getNeedLoginPages,
- } from '@/utils/needLoginPages.js'
- // 登录页
- const LOGIN_ROUTE = '/pages/login/index'
- // 是否开发环境
- const isDev = process.env.NODE_ENV === 'development'
- // 拦截器主体
- const routeGuard = {
- invoke({ url }) {
- // 1️⃣ 解析纯路径(去掉 query)
- const path = url.split('?')[0]
- // 2️⃣ 获取需要登录的页面列表
- const needLoginPages = isDev
- ? getNeedLoginPages()
- : _needLoginPages
- // 3️⃣ 是否命中黑名单
- const needLogin = needLoginPages.includes(path)
- // 4️⃣ 是否已登录
- const hasToken = userToken.value
- // 5️⃣ 放行条件
- if (!needLogin || hasToken) {
- return true
- }
- // 6️⃣ 未登录 → 跳登录页
- uni.navigateTo({
- url: LOGIN_ROUTE,
- })
- // ⚠️ 必须 return false
- return false
- },
- }
- // 对外安装方法
- export const routeInterceptor = {
- install() {
- uni.addInterceptor('navigateTo', routeGuard)
- uni.addInterceptor('redirectTo', routeGuard)
- uni.addInterceptor('reLaunch', routeGuard)
- uni.addInterceptor('switchTab', routeGuard)
- },
- }
|