1.0.0 • Published 5 years ago

route-guards v1.0.0

Weekly downloads
-
License
ISC
Repository
github
Last release
5 years ago

route-guards 路由守卫

介绍

uniapp 中模拟并实现对应vue-router的部分 Api 的功能

平台差异说明

AppH5微信小程序支付宝小程序百度小程序头条小程序QQ 小程序360 小程序

全局前置守卫

// main.js

import UniGuard from './lib';

const guard = new UniGuard();

guard.beforeEach((to, from, next) => {
    console.log('========================');
    console.log('guard.beforeEach');
    console.log('to: ', to);
    console.log('from: ', from);

    if (to.url.includes('id=1')) {
        next({ url: '/pages/C' });

        // 或者也可以使用一下方法
        // next({
        //     url: '/pages/D',
        //     action: 'navigateTo'
        // });
        // next(false);
        // next(new Error("can`t redirect "));
    } else {
        next();
    }
});

全局后置后卫

guard.afterEach((to, from) => {
    console.log('========================');
    console.log('guard.afterEach');
    console.log('to: ', to);
    console.log('from: ', from);
});

路由运行出时调用的守卫

guard.onError((errMsg) => {
    console.log('my route-guards error: ' + errMsg);
});

如何跳转路由并触发注册的守卫

路由跳转的使用方法和 uniapp 路由跳转一样的

// 例如
uni.navigateTo({ url: '/pages/a' });
uni.redirectTo({ url: '/pages/a' });
uni.reLaunch({ url: '/pages/a' });
uni.switchTab({ url: '/pages/a' });
uni.navigateBack();

解析运行流程

  • 调用全局的beforeEach守卫
  • 路由跳转
  • 调用全局的afterEach守卫

注意

暂不支持如下操作:

guard.beforeEach((to, from, next) => {
    next((vm) => {
        // 通过 `vm` 访问组件实例
    });
});

Api

Event

参数名称类型默认值是否必填说明
beforeEachFunction-false注册一个回调,在路由跳转之前运行
afterEachFunction-false注册一个回调,在路由跳转之后运行
onErrorFunction-false注册一个回调,该回调会在路由导航过程中出错时被调用
1.0.0

5 years ago