效果展示
新建interceptors文件夾
新建文件route.ts
/**
* 路由攔截塞颁,通常也是登錄攔截
* 可以設(shè)置路由白名單处面,或者黑名單扯再,看業(yè)務(wù)需要選哪一個(gè)
* 我這里應(yīng)為大部分都可以隨便進(jìn)入诱咏,所以使用黑名單
*/
import { getNeedLoginPages, needLoginPages as _needLoginPages } from '@/utils'
// TODO Check
const loginRoute = '/pages/login/login'
const isLogined = () => {
return false
}
const isDev = true
// 黑名單登錄攔截器 - (適用于大部分頁面不需要登錄事甜,少部分頁面需要登錄)
const navigateToInterceptor = {
// 注意兔沃,這里的url是 '/' 開頭的玛迄,如 '/pages/index/index'狡逢,跟 'pages.json' 里面的 path 不同
invoke({ url }: { url: string }) {
// console.log(url) // /pages/route-interceptor/index?name=feige&age=30
const path = url.split('?')[0]
let needLoginPages: string[] = []
// 為了防止開發(fā)時(shí)出現(xiàn)BUG宁舰,這里每次都獲取一下。生產(chǎn)環(huán)境可以移到函數(shù)外奢浑,性能更好
if (isDev) {
needLoginPages = getNeedLoginPages()
} else {
needLoginPages = _needLoginPages
}
const isNeedLogin = needLoginPages.includes(path)
if (!isNeedLogin) {
return true
}
const hasLogin = isLogined()
if (hasLogin) {
return true
}
const redirectRoute = `${loginRoute}?redirect=${encodeURIComponent(url)}`
uni.navigateTo({ url: redirectRoute })
return false
},
}
export const routeInterceptor = {
install() {
uni.addInterceptor('navigateTo', navigateToInterceptor)
uni.addInterceptor('reLaunch', navigateToInterceptor)
uni.addInterceptor('redirectTo', navigateToInterceptor)
uni.addInterceptor('switchTab', navigateToInterceptor)
},
}
新建index.ts
export { routeInterceptor } from './route'
新建utils文件夾
新建index.ts文件
import { pages, subPackages, tabBar } from '@/pages.json'
/** 判斷當(dāng)前頁面是否是tabbar頁 */
export const getIsTabbar = () => {
if (!tabBar) {
return false
}
if (!tabBar.list.length) {
// 通常有tabBar的話蛮艰,list不能有空,且至少有2個(gè)元素雀彼,這里其實(shí)不用處理
return false
}
// getCurrentPages() 至少有1個(gè)元素壤蚜,所以不再額外判斷
const lastPage = getCurrentPages().at(-1)
const currPath = lastPage.route
return !!tabBar.list.find((e) => e.pagePath === currPath)
}
/**
* 獲取當(dāng)前頁面路由的 path 路勁和 redirectPath 路徑
* path 如 ‘/pages/login/index’
* redirectPath 如 ‘/pages/demo/base/route-interceptor’
*/
export const currRoute = () => {
// getCurrentPages() 至少有1個(gè)元素,所以不再額外判斷
const lastPage = getCurrentPages().at(-1)
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)
// 經(jīng)過多端測(cè)試徊哑,只有 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) // 這里需要統(tǒng)一 decodeURIComponent 一下,可以兼容h5和微信y
})
return { path, query }
}
/**
* 得到所有的需要登錄的pages莺丑,包括主包和分包的
* 這里設(shè)計(jì)得通用一點(diǎn)著蟹,可以傳遞key作為判斷依據(jù),默認(rèn)是 needLogin, 與 route-block 配對(duì)使用
* 如果沒有傳 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 } = subPageObj
subPageObj.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 數(shù)組
*/
export const getNeedLoginPages = (): string[] => getAllPages('needLogin').map((page) => page.path)
/**
* 得到所有的需要登錄的pages,包括主包和分包的
* 只得到 path 數(shù)組
*/
export const needLoginPages: string[] = getAllPages('needLogin').map((page) => page.path)
下面是pages.json文件炕横,把需要登錄的頁面設(shè)置上"needLogin":true,
{
"pages": [ //pages數(shù)組中第一項(xiàng)表示應(yīng)用啟動(dòng)頁源内,參考:https://uniapp.dcloud.io/collocation/pages
{
"path": "pages/index/index",
"style": {
"navigationBarTitleText": "首頁"
}
},
{
"path": "pages/Mine/Mine",
"needLogin":true,
"style": {
"navigationBarTitleText": "我的",
"navigationStyle": "custom"
}
},
{
"path" : "pages/Waterfall/Waterfall",
"needLogin":true,
"style" :
{
"navigationBarTitleText" : "瀑布流"
}
},
{
"path" : "pages/login/login",
"style" :
{
"navigationBarTitleText" : "登錄"
}
}
],
"globalStyle": {
"navigationBarTextStyle": "black",
"navigationBarTitleText": "uni-app",
"navigationBarBackgroundColor": "#F8F8F8"
// "backgroundColor": "#F8F8F8"
},
"uniIdRouter": {},
"tabBar": {
"color": "#7A7E83",
"selectedColor": "#1296db",
"borderStyle": "black",
"backgroundColor": "#ffffff",
"list": [{
"pagePath": "pages/index/index",
"iconPath": "static/ic_tab_home_unselect.png",
"selectedIconPath": "static/ic_tab_home_select.png",
"text": "首頁"
},{
"pagePath": "pages/Waterfall/Waterfall",
"iconPath": "static/ic_tab_home_unselect.png",
"selectedIconPath": "static/ic_tab_home_select.png",
"text": "瀑布流"
}, {
"pagePath": "pages/Mine/Mine",
"iconPath": "static/ic_tab_mine_unselect.png",
"selectedIconPath": "static/ic_tab_mine_select.png",
"text": "我的"
}]
},
"subPackages": []
}
main.js引入
然后再main.js中引入監(jiān)聽
import App from './App'
import { routeInterceptor} from './interceptors'
// #ifndef VUE3
import Vue from 'vue'
import './uni.promisify.adaptor'
Vue.config.productionTip = false
App.mpType = 'app'
const app = new Vue({
...App
})
app.$mount()
// #endif
// #ifdef VUE3
import { createSSRApp } from 'vue'
export function createApp() {
const app = createSSRApp(App)
app.use(routeInterceptor)
return {
app
}
}
// #endif