欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 教育 > 锐评 > uniapp通过uni.addInterceptor实现路由拦截

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

2025/5/18 0:04:50 来源:https://blog.csdn.net/Shh_1758668879/article/details/147308428  浏览:    关键词:uniapp通过uni.addInterceptor实现路由拦截

注:此拦截不能首次拦截路由跳转的方法('switchTab', 'navigateTo', 'reLaunch', 'redirectTo'),拦截request请求api可以

1. app.vue 代码

	import { onLaunch} from '@dcloudio/uni-app'import permission  from './utils/permission'onLaunch(()=>{console.log('我是APP蓝翅')uni.request({url: 'https://apifoxmock.com/m1/4728220-0-default/api/user/getBanner',method: 'GET',success: (res)=>{console.log('res')}})permission()})

2. permission 代码

const checkAuth = function() {// 拦截器的API列表const apiList = ['switchTab', 'navigateTo', 'reLaunch', 'redirectTo']// 白名单列表const whitePath = ['/pages/logic/logic']apiList.map(item => {uni.addInterceptor(item, {invoke(args) {console.log(args)// 取出当前路由地址const path = args.url.split('?')[0]// 此处通过token来模拟是否登录,具体的根据项目来判断const token = uni.getStorageSync('token')console.log(token)// 判断是否在白名单内if (whitePath.includes(path)) {console.log('不需要登录')return } else {if (token) {console.log('登录')// 登录了return} else {console.log('没有登录')// 未登录uni.navigateTo({url: `/pages/logic/logic?redirectTo=${encodeURIComponent(args.url)}`})return false}}}})})
}export default checkAuth

3. 登录简单实现代码

<template><view class="page-wrap">用户名:<input type="text" border="surround" v-model="username" /><up-button type="primary" @click="login">登录</up-button></view>
</template><script setup>import {ref} from 'vue'import {onShow,onLoad} from '@dcloudio/uni-app'const username = ref('')const redirectPath = ref('')onLoad((p)=>{console.log(p)})onShow((props) => {console.log(props)console.log(redirectPath.value)console.log(getCurrentPages())const page = getCurrentPages()let currentPage = page[page.length - 1]redirectPath.value = currentPage?.$page?.options?.redirectTo || ''})const login = () => {if (username.value) {uni.setStorageSync('token', username)console.log((redirectPath.value))uni.redirectTo({url: decodeURIComponent(redirectPath.value),fail: (err) => {console.log(err)uni.switchTab({url: decodeURIComponent(redirectPath.value),})}})} else {uni.showToast({title: '请输入用户名'})}}
</script><style scoped>.page-wrap {padding: 20rpx;}
</style>

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词