使用uni-app原生方式实现登录鉴权,路由拦截
在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
})
}
}
组件使用
listAddress(){
this.$href("../address/list?back=1")
},
uni-simple-router 路由、拦截、最优雅的解决方案
uni-simple-router 插件,在uni-app中使用vue-router的方式进行跳转路由,路由拦截
官网地址:https://hhyang.cn/v2/start/quickstart.html
路由拦截的小细节:
- 在vue.config.js中修改includes属性,添加"meta",这样可以在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
}
}
- 路由拦截的代码,可以携带上要去的路径,在登录完成后再次进行跳转
//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'
})
}
}