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 # 处理跨域   
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
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`来移除拦截器。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值