uniapp通过uni.addInterceptor实现路由拦截功能

扒了插件市场的uni-start,抽出来的简单的路由拦截功能。

项目结构
|--
    |-- App.vue
    |-- index.html
    |-- main.js
    |-- manifest.json
    |-- pages.json
    |-- uni.scss
    |-- .hbuilderx
    |   |-- launch.json
    |-- api # api文件
    |-- components # 自定义组件,按照格式:组件名/组件名.vue,使用组件时无需引入,直接使用即可
    |-- pages	# 页面
    |-- static # 静态资源
    |-- store # vuex存储
    |   |-- getters.js
    |   |-- index.js
    |   |-- modules
    |       |-- app.js
    |       |-- user.js
    |-- styles # 样式文件
    |   |-- theme.scss
    |-- uni_modules # ui组件
    |-- utils
        |-- auth.js # 权限存储函数
        |-- constant.js # 常量,如api前缀
        |-- index.js # 公共方法
        |-- mixin.js # mixin,主题切换、登录校验
        |-- permission.js # 路由拦截
        |-- request.js # 请求拦截,请求响应统一处理
   	|-- vue.config.js # 处理跨域   
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)
}
permission.js

未登录时对路由进行拦截,白名单不拦截

/**
 * @description 自定义路由拦截
 */

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

// 白名单
const whiteList = [
  '/', // 注意入口页必须直接写 '/'
  { pattern: /^\/pages\/list.*/ }, // 支持正则表达式
  '/pages/grid/grid',
  '/pages/user-center/user-center',
  { pattern: /^\/pages\/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
<script>
import routingIntercept from '@/utils/permission.js'
export default {
  globalData: {
    searchText: ''
  },
  onLaunch: function() {
    // 对路由进行统一拦截,实现路由导航守卫 router.beforeEach 功能
    routingIntercept()
  },
  onShow: function() {
    console.log('App Show')
  },
  onHide: function() {
    console.log('App Hide')
  }
}
</script>

<style>
	/*每个页面公共css */
</style>
  • 14
    点赞
  • 51
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
Uni-app中,你可以使用`uni.request`方法发送网络请求,并使用`uni.addInterceptor`方法添加拦截器来对请求进行拦截和处理。下面是一个示例: 1. 在`main.js`文件中引入`uni.request`方法和`uni.addInterceptor`方法: ```javascript import Vue from 'vue' import App from './App' Vue.config.productionTip = false Vue.prototype.$http = uni.request Vue.prototype.$addInterceptor = uni.addInterceptor App.mpType = 'app' const app = new Vue({ ...App }) app.$mount() ``` 2. 在需要使用的页面中,使用`uni.addInterceptor`方法添加拦截器: ```javascript export default { methods: { requestInterceptor() { // 添加请求拦截器 this.$addInterceptor('request', (config) => { // 在发送请求之前可以对请求参数进行处理 console.log('请求拦截器 - 请求参数:', config) return config }) // 添加响应拦截器 this.$addInterceptor('response', (response) => { // 在接收到响应数据之后可以对数据进行处理 console.log('响应拦截器 - 响应数据:', response) return response }) }, removeInterceptor() { // 移除拦截器 this.$addInterceptor('request', undefined) this.$addInterceptor('response', undefined) } }, mounted() { this.requestInterceptor() // 发起请求 this.$http({ url: 'https://api.example.com', method: 'GET', data: { // 请求参数 }, success: (res) => { // 请求成功回调 console.log('请求成功:', res) }, fail: (err) => { // 请求失败回调 console.log('请求失败:', err) } }) // 移除拦截器 this.removeInterceptor() } } ``` 在示例中,通过`this.$addInterceptor`方法添加请求拦截器和响应拦截器,可以在拦截器内部对请求和响应进行处理。你可以根据自己的需求在拦截器中对请求和响应进行操作。注意,在不需要拦截器的时候,可以使用`this.$addInterceptor`方法将拦截器设置为`undefined`来移除拦截器。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值