路由拦截是开发中常见场景,比如校验用户是否登录、路由拦截添加弹窗等。通过setInterception可以实现这些功能,该需求主要用于路由拦截前调用开发者设置的拦截回调,和拦截回调里开发者返回处理后需要跳转的页面信息 。
场景一:判断用户是否登录。
方案:
设置并开启页面路由拦截registerInterception,通过全局变量LocalStorage判断用户当前是否登录,未登录时点击购物车会被拦截并跳转至登录页,输入用户名和密码后将LocalStorage改为true表示已登录,然后跳转至购物车。
核心代码
设置willShow页面跳转前拦截,当从首页跳转(即typeof from === “string”)时,如果此时登录状态为false(!this.storageLink)且目标页为购物车(target.pathInfo.name === ‘pageTwo’),则会将跳转的目标页pop,然后跳转至登录页登录。
registerInterception() {
let loginIntercept:InterceptionShowCallback = (from: NavDestinationContext | "navBar", to: NavDestinationContext | "navBar") => {
if (!this.isUseInterception) {
return;
}
if (typeof from === 'string') {
let target: NavDestinationContext = to as NavDestinationContext;
console.log("source page is navigation home");
if (!this.storageLink && target.pathInfo.name === 'pageTwo') {
target.pathStack.pop();
target.pathStack.pushPathByName('pageOne', null);
}
}
}
}