Uniapp路由攔截(跳轉(zhuǎn)登錄)

效果展示

新建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
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市份殿,隨后出現(xiàn)的幾起案子膜钓,更是在濱河造成了極大的恐慌,老刑警劉巖卿嘲,帶你破解...
    沈念sama閱讀 219,490評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件颂斜,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡拾枣,警方通過查閱死者的電腦和手機(jī)沃疮,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,581評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來梅肤,“玉大人司蔬,你說我怎么就攤上這事∫毯” “怎么了俊啼?”我有些...
    開封第一講書人閱讀 165,830評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵,是天一觀的道長左医。 經(jīng)常有香客問我授帕,道長,這世上最難降的妖魔是什么浮梢? 我笑而不...
    開封第一講書人閱讀 58,957評(píng)論 1 295
  • 正文 為了忘掉前任跛十,我火速辦了婚禮,結(jié)果婚禮上秕硝,老公的妹妹穿的比我還像新娘芥映。我一直安慰自己,他們只是感情好远豺,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,974評(píng)論 6 393
  • 文/花漫 我一把揭開白布奈偏。 她就那樣靜靜地躺著,像睡著了一般憋飞。 火紅的嫁衣襯著肌膚如雪霎苗。 梳的紋絲不亂的頭發(fā)上姆吭,一...
    開封第一講書人閱讀 51,754評(píng)論 1 307
  • 那天榛做,我揣著相機(jī)與錄音,去河邊找鬼。 笑死检眯,一個(gè)胖子當(dāng)著我的面吹牛厘擂,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播锰瘸,決...
    沈念sama閱讀 40,464評(píng)論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼刽严,長吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了避凝?” 一聲冷哼從身側(cè)響起舞萄,我...
    開封第一講書人閱讀 39,357評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎管削,沒想到半個(gè)月后倒脓,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,847評(píng)論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡含思,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,995評(píng)論 3 338
  • 正文 我和宋清朗相戀三年崎弃,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片含潘。...
    茶點(diǎn)故事閱讀 40,137評(píng)論 1 351
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡饲做,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出遏弱,到底是詐尸還是另有隱情盆均,我是刑警寧澤,帶...
    沈念sama閱讀 35,819評(píng)論 5 346
  • 正文 年R本政府宣布腾窝,位于F島的核電站缀踪,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏虹脯。R本人自食惡果不足惜驴娃,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,482評(píng)論 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望循集。 院中可真熱鬧唇敞,春花似錦、人聲如沸咒彤。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,023評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽镶柱。三九已至旷档,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間歇拆,已是汗流浹背鞋屈。 一陣腳步聲響...
    開封第一講書人閱讀 33,149評(píng)論 1 272
  • 我被黑心中介騙來泰國打工范咨, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人厂庇。 一個(gè)月前我還...
    沈念sama閱讀 48,409評(píng)論 3 373
  • 正文 我出身青樓渠啊,卻偏偏與公主長得像,于是被迫代替她去往敵國和親权旷。 傳聞我的和親對(duì)象是個(gè)殘疾皇子替蛉,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,086評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容