uni-app项目封装跳转拦截

封装缓存

tools.js

// 缓存
export const useSession = ()=> {
	const setItem = (key,value) =>{
		uni.setStorageSync(key,JSON.stringify(value))
		// sessionStorage.setItem(key,)
	}
	
	const getItem = (key)=>{
		let returnVal = uni.getStorageSync(key)
		if(returnVal){
			 returnVal = JSON.parse(uni.getStorageSync(key))
		}
		
		return returnVal
		// uni.setStorageSync(key,JSON.stringify(value))
		// return JSON.parse(sessionStorage.getItem(key))
	} 
	
	const removeItem = (key) => {
		uni.removeStorageSync(key)
	}
	
	return {
		setItem,
		getItem,
		removeItem,
		timeStamp
	}
}  

跳转拦截

permission.js

import { useSession } from '@/utils/tools.js'

const session = useSession()

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

export default async function() {
	const list = ['navigateTo', 'redirectTo', 'reLaunch', 'switchTab']
	
	// 添加全局路由拦截
	list.forEach(item => {
		uni.addInterceptor(item, {
		  // 路由前拦截
		  invoke(args) {
			console.log('navigateTo路由跳转成功', args);
			const token = session.getItem('token')
			const url = args.url.split('?')[0]
		    if (token) {
				if (args.url.includes('/pages/binding/binding') || args.url.includes('/pages/login/login')) {
					//跳转到首页
					uni.navigateTo({
					  url: '/pages/index/index',
					});
					
					return false;
				}
				
				return args;
		    } else {
				let pass;
				if (whiteList) {
					pass = whiteList.some((whiteItem) => {
						if (typeof (whiteItem) === 'object' && whiteItem.pattern) {
							return whiteItem.pattern.test(url)
						}
						return url === whiteItem
					})
				}
				console.log('pass', pass)
				
				if(!pass) {
					uni.showToast({
						title: '请先登录',
						icon: 'none'
					})
					
					uni.navigateTo({
						url: "/pages/login/login"
					})
					
					return false
				}
		        return args;
		    }
		  },
		  // 路由后拦截
		  success(res) {
		  },
		  fail(err) {
		  }
		});
	})
}

引入

可以在main.js中进行引入(要注意执行顺序),也可以在App.vue中的onLaunch函数中执行

App.vue

import routingIntercept from '@/utils/permission.js'

export default {
  onLaunch: function() {
  	//路由拦截
	routingIntercept()
  }
}

你可能感兴趣的:(vue,uni-app,vue)