Uni-app routing interception and uni-simple-router routing, interception, the most elegant solution

Use uni-app native way to realize login authentication and route interception

Add the following code in main.js

//任何组件在跳转xx页面时调用此方法,判断token,false就跳转到login页面,并携带xx页面路径。
//登录成功后重新跳转回xx页面

Vue.prototype.$href=function(data,type=1){
    
    
	if(uni.getStorageSync("token")){
    
    
		if(type==1){
    
    
			uni.navigateTo({
    
    
				url:data
			})
		}
		if(type==2){
    
    
			uni.switchTab({
    
    
				url:data
			})
		}
		
	}else{
    
    
		uni.navigateTo({
    
    
			url:"/pages/login/login?backurl="+data
		})
	}
}

Component usage

			listAddress(){
    
    
				this.$href("../address/list?back=1")
			},

uni-simple-router routing, interception, the most elegant solution

uni-simple-router plug-in, use vue-router in uni-app for redirect routing and route interception

Official website address: https://hhyang.cn/v2/start/quickstart.html

Small details of route interception:

  1. Modify the includes attribute in vue.config.js and add "meta" so that you can get the new attribute in page.json
//vue.config.js
includes: ['path', 'name', 'aliasPath','meta']
//page.json 需要登录鉴权的页面添加meta属性
	    {
    
    
            "path" : "pages/children/address/address",
			"name":"address",
			"meta":{
    
    "loginAuth":true},
            "style" :                                                                                    
            {
    
    
                "navigationBarTitleText": "",
                "enablePullDownRefresh": false
            }
        }
  1. The route intercepted code can carry the path to go, and then jump again after the login is completed
//router.js
//全局路由前置守卫
router.beforeEach((to, from, next) => {
    
    
	console.log(to)
	if(to.meta.loginAuth){
    
    
		let token=uni.getStorageSync('token')
		if(token){
    
    
			next()
		}else{
    
    
			uni.navigateTo({
    
    
				url:'/pages/login/login?path='+to.path
			})
		}
	}else{
    
    
		next();
	}
	
	
});

//在login组件进行修改
login(){
    
    
//跳转页面
	if (this.$route.query.path) {
    
    
		this.$router.push(this.$route.query)
	} else {
    
    
		uni.switchTab({
    
    
		url: '/pages/admin/admin'
		})
	}
}

Guess you like

Origin blog.csdn.net/weixin_51198863/article/details/114043359