uni-app路由拦截

2 篇文章 0 订阅

新建一个auth.js

/**
 * @description 权限存储函数
 */
const authorizationKey = 'Authorization'

export function getAuthorization() {
  return uni.getStorageSync(authorizationKey)
}

export function setAuthorization(authorization) {
  return uni.setStorageSync(authorizationKey, authorization)
}

export function removeAuthorization(authorization) {
  return uni.removeStorageSync(authorizationKey)
}

新建route.js

import { getAuthorization } from '@/utils/auth.js'

// 白名单
const whiteList = [
  '/', // 注意入口页必须直接写 '/'
  '/pages/Login/Login'
]

export default async function() {
  const list = ['navigateTo', 'redirectTo', 'reLaunch', 'switchTab']
  // 用遍历的方式分别为,uni.navigateTo,uni.redirectTo,uni.reLaunch,uni.switchTab这4个路由方法添加拦截器
  list.forEach(item => {
    uni.addInterceptor(item, {
      invoke(e) {
        // 获取要跳转的页面路径(url去掉"?"和"?"后的参数)
        const url = e.url.split('?')[0]
        console.log('url', url)

        // 判断当前窗口是白名单,如果是则不重定向路由
        let pass
        if (whiteList) {
          pass = whiteList.some((item) => {
            if (typeof (item) === 'object' && item.pattern) {
              return item.pattern.test(url)
            }
            return url === item
          })
        }

        // 不是白名单并且没有token
        if (!pass && !getAuthorization()) {
          uni.showToast({
            title: '请先登录',
            icon: 'none'
          })
          uni.navigateTo({
            url: "/pages/Login/Login"
          })
          return false
        }
        return e
      },
      fail(err) { // 失败回调拦截
        console.log(err)
      }
    })
  })
}

APP.vue

import routingIntercept from '@/router/route.js'
    export default {
        onLaunch: function() {
            console.log('App Launch');
            // 对路由进行统一拦截,实现路由导航守卫 router.beforeEach 功能
            routingIntercept()
        },
        onShow: function() {
            console.log('App Show')
        },
        onHide: function() {
            console.log('App Hide')
        }
    }
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值