1.引言
路由攔截,個人理解就是在頁面跳轉的時候,增加一級攔截器,實現一些自定義的功能,其中最重要的就是判斷跳轉的頁面是否需要登錄后查看,如果需要登錄后查看且此時系統并未登錄,就需要跳轉到登錄頁,登錄后跳轉到原來想要訪問的頁面。
2.實現
uni-app的路由跳轉分別是uni.navigateTo:保留當前頁面,跳轉到應用內的某個頁面,使用uni.navigateBack
可以返回到原頁面;uni.redirectTo:關閉當前頁面,跳轉到應用內的某個頁面;uni.reLaunch:關閉所有頁面,打開到應用內的某個頁面;uni.switchTab:跳轉到 tabBar 頁面,并關閉其他所有非 tabBar 頁面;uni.navigateBack:關閉當前頁面,返回上一頁面或多級頁面,可通過?getCurrentPages()
?獲取當前的頁面棧,決定需要返回幾層。
在進行路由跳轉時,通過uni.addInterceptor,添加攔截器,實現路由攔截。
攔截是否需要登錄的基本思路是通過pages.json文件對應的配置needLogin,進行頁面的配置,在攔截時,找到有此配置的所有頁面,得到所有頁面的路徑,和本次訪問的路徑進行匹配,如果匹配成功,則判斷當前是否是登錄狀態,若沒有登錄,跳轉到登錄界面,進行登錄。
3.代碼
代碼主要分為攔截器代碼,登錄頁pages配置,登錄頁登錄按鈕功能。
1.攔截器代碼
/*** by 菲鴿 on 2024-03-06* 路由攔截,通常也是登錄攔截* 可以設置路由白名單,或者黑名單,看業務需要選哪一個* 我這里應為大部分都可以隨便進入,所以使用黑名單*/
import { useUserStore } from '@/store'
import { getNeedLoginPages, needLoginPages as _needLoginPages } from '@/utils'
import { getAccessToken } from '@/utils/auth'// 登錄頁面路徑
const loginRoute = '/pages/login/index'const isLogined = () => {const userStore = useUserStore()return userStore.userInfo.isLogin && getAccessToken()
}const isDev = import.meta.env.DEV// 黑名單登錄攔截器 - (適用于大部分頁面不需要登錄,少部分頁面需要登錄)
const navigateToInterceptor = {// 注意,這里的url是 '/' 開頭的,如 '/pages/index/index',跟 'pages.json' 里面的 path 不同invoke({ url }: { url: string }) {console.log(url) // /pages/route-interceptor/index?name=feige&age=30const path = url.split('?')[0]let needLoginPages: string[] = []// 為了防止開發時出現BUG,這里每次都獲取一下。生產環境可以移到函數外,性能更好if (isDev) {needLoginPages = getNeedLoginPages()} else {needLoginPages = _needLoginPages}const isNeedLogin = needLoginPages.includes(path)if (!isNeedLogin || isLogined()) {return true}const redirectRoute = `${loginRoute}?redirect=${encodeURIComponent(url)}`console.log(redirectRoute)uni.navigateTo({ url: redirectRoute })return false},
}export const routeInterceptor = {install() {uni.addInterceptor('navigateTo', navigateToInterceptor)uni.addInterceptor('reLaunch', navigateToInterceptor)uni.addInterceptor('redirectTo', navigateToInterceptor)},
}
2.輔助函數代碼
import { pages, subPackages, tabBar } from '@/pages.json'
export const getLastPage = () => {// getCurrentPages() 至少有1個元素,所以不再額外判斷// const lastPage = getCurrentPages().at(-1)// 上面那個在低版本安卓中打包回報錯,所以改用下面這個【雖然我加了src/interceptions/prototype.ts,但依然報錯】const pages = getCurrentPages()return pages[pages.length - 1]
}/** 判斷當前頁面是否是tabbar頁 */
export const getIsTabbar = () => {if (!tabBar) {return false}if (!tabBar.list.length) {// 通常有tabBar的話,list不能有空,且至少有2個元素,這里其實不用處理return false}const lastPage = getLastPage()const currPath = lastPage.routereturn !!tabBar.list.find((e) => e.pagePath === currPath)
}/*** 獲取當前頁面路由的 path 路徑 和 redirectPath 路徑* path 如 ‘/pages/login/index’* redirectPath 如 ‘/pages/demo/base/route-interceptor’*/
export const currRoute = () => {const lastPage = getLastPage()const currRoute = (lastPage as any).$page// console.log('lastPage.$page:', currRoute)// console.log('lastPage.$page.fullpath:', currRoute.fullPath)// console.log('lastPage.$page.options:', currRoute.options)// console.log('lastPage.options:', (lastPage as any).options)// 經過多端測試,只有 fullPath 靠譜,其他都不靠譜const { fullPath } = currRoute as { fullPath: string }// console.log(fullPath)// eg: /pages/login/index?redirect=%2Fpages%2Fdemo%2Fbase%2Froute-interceptor (小程序)// eg: /pages/login/index?redirect=%2Fpages%2Froute-interceptor%2Findex%3Fname%3Dfeige%26age%3D30(h5)return getUrlObj(fullPath)
}const ensureDecodeURIComponent = (url: string) => {if (url.startsWith('%')) {return ensureDecodeURIComponent(decodeURIComponent(url))}return url
}
/*** 解析 url 得到 path 和 query* 比如輸入url: /pages/login/index?redirect=%2Fpages%2Fdemo%2Fbase%2Froute-interceptor* 輸出: {path: /pages/login/index, query: {redirect: /pages/demo/base/route-interceptor}}*/
export const getUrlObj = (url: string) => {const [path, queryStr] = url.split('?')// console.log(path, queryStr)if (!queryStr) {return {path,query: {},}}const query: Record<string, string> = {}queryStr.split('&').forEach((item) => {const [key, value] = item.split('=')// console.log(key, value)query[key] = ensureDecodeURIComponent(value) // 這里需要統一 decodeURIComponent 一下,可以兼容h5和微信y})return { path, query }
}
/*** 得到所有的需要登錄的pages,包括主包和分包的* 這里設計得通用一點,可以傳遞key作為判斷依據,默認是 needLogin, 與 route-block 配對使用* 如果沒有傳 key,則表示所有的pages,如果傳遞了 key, 則表示通過 key 過濾*/
export const getAllPages = (key = 'needLogin') => {// 這里處理主包const mainPages = [...pages.filter((page) => !key || page[key]).map((page) => ({...page,path: `/${page.path}`,})),]// 這里處理分包const subPages: any[] = []subPackages.forEach((subPageObj) => {// console.log(subPageObj)const { root } = subPageObjsubPageObj.pages.filter((page) => !key || page[key]).forEach((page: { path: string } & Record<string, any>) => {subPages.push({...page,path: `/${root}/${page.path}`,})})})const result = [...mainPages, ...subPages]// console.log(`getAllPages by ${key} result: `, result)return result
}/*** 得到所有的需要登錄的pages,包括主包和分包的* 只得到 path 數組*/
export const getNeedLoginPages = (): string[] => getAllPages('needLogin').map((page) => page.path)/*** 得到所有的需要登錄的pages,包括主包和分包的* 只得到 path 數組*/
export const needLoginPages: string[] = getAllPages('needLogin').map((page) => page.path)
3.需要登錄頁面配置
<route lang="json5">
{style: {navigationBarTitleText: '辦公',},needLogin: true,
}
</route>
<template><view class="bg-white overflow-hidden pt-2 px-4"><view>123</view></view>
</template><script setup lang="ts"></script><style lang="scss"></style>
能在組件中配置頁面的信息,主要得益于@uni-helper/vite-plugin-uni-pages
?插件的功勞,該插件由?uni-helper
?官方團隊開發,可參考uni 插件 | unibest。
4.登錄按鈕功能
// 登錄系統 一進系統就需要登錄
const handleLogin = async () => {const loginRes = await loginApi.login(loginForm)console.log(loginRes)setAccessToken(loginRes.data.accessToken)setRefreshToken(loginRes.data.refreshToken)// 獲取路由路徑 進行跳轉const fullPath = currRoute()console.log(fullPath)uni.redirectTo({ url: fullPath.query.redirect })
}
登錄按鈕就是獲取登錄數據,存儲token,重定向至原來訪問的界面。
4.功能展示
uni-app登錄驗證
5.寫在最后
本文首先感謝unibestuniapp
?開發框架,在unibest項目基礎上,添加了一些小的功能,基本能滿足路由跳轉時的攔截,為后續業務的權限管理打下堅實基礎。
本文如有疏漏之處,歡迎批評指正。