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

// 黑名單登錄攔截器 - (適用于大部分頁(yè)面不需要登錄,少部分頁(yè)面需要登錄)
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)前頁(yè)面是否是tabbar頁(yè)  */
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)前頁(yè)面路由的 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)過(guò)多端測(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, 則表示通過(guò) key 過(guò)濾
 */
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文件,把需要登錄的頁(yè)面設(shè)置上"needLogin":true,

{
    "pages": [ //pages數(shù)組中第一項(xiàng)表示應(yīng)用啟動(dòng)頁(yè),參考:https://uniapp.dcloud.io/collocation/pages
        {
            "path": "pages/index/index",
            "style": {
                "navigationBarTitleText": "首頁(yè)"
            }
        },
        {
            "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": "首頁(yè)"
        },{
            "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)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容