Vue.js和微信小程序路由(页面)跳转拦截
在开发有登录功能的项目时,不可避免的需要在路由(页面)跳转时对当前用户的权限进行一定的校验。目前我使用的比较多的Vue.js提供了比较好的解决方案,在开发微信小程序时,发现官方目前并未提供相应的解决方案,所以在社区和掘金寻找并选择合适自己项目的方案。
Vue.js的路由拦截
//router.js
export const constantRoutes = [
/**
* @description: 登录界面
*/
{
path: '/login',
component: () => import('@/views/login/index'),
hidden: true
},
{
path: '/',
redirect: '/capture',
hidden: true
},
{
path: '/404',
component: () => import('@/views/404.vue'),
hidden: true
},
]
permission.js
router.beforeEach(async(to, from, next) => {
const hasToken=''
// 判断是否登录
if (hasToken) {
next()
}else{
//没有登录就返回登录页面
}
})
小程序有木有类似路由跳转拦截呢?
第一种是重写page
// utils/filter.js
function loginCheck(pageObj) {
if (pageObj.onLoad) {
let _onLoad = pageObj.onLoad;
// 使用onLoad的话需要传递options
pageObj.onLoad = function (options) {
if(wx.getStorageSync('USERID')) {
// 获取当前页面
let currentInstance = getPageInstance();
_onLoad.call(currentInstance, options);
} else {
//跳转到登录页
wx.redirectTo({
url: "/pages/login/login"
});
}
}
}
return pageObj;
}
// 获取当前页面
function getPageInstance() {
var pages = getCurrentPages();
return pages[pages.length - 1];
}
exports.loginCheck = loginCheck;
在需要使用的页面引入上面的过滤函数该方法即可: 如:
// pages/user/user.js
const filter = require('../../utils/filter');
Page(filter.loginCheck({
// ...
onLoad: function (options) {
// ...
},
// ...
}));
第二种是使用 Object.defineProperty监听小程序跳转方法
// 在app.js
const navigateTo = wx.navigateTo
const myNavigateTo = function(options){
console.log('navigateTo')
wx.showToast({
title: 'title',
success:function(){
// 验证成功后跳转
navigateTo(options)
}
})
}
Object.defineProperty(wx, "navigateTo", {
configurable: true,
enumerable: true,
get: function () {
return myNavigateTo
}
})
在需要使用的页面引入上面的过滤函数该方法即可: 如:
// pages/user/user.js
Page({
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
使用方法和之前的微信跳转一样
wx.navigateTo({
url:'/pages/logs/logs'
})
}
})