z-router-middleware-guard
Version:
a middleware guard plugin of vue-router 4.0
127 lines (106 loc) • 3.33 kB
JavaScript
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.ZOssImage = {}));
}(this, (function (exports) { 'use strict';
var LifecycleHook = /*#__PURE__*/function () {
function LifecycleHook(hook) {
this.hook = hook;
/**
* 收集前置路由守卫中间件
*/
this.beforeQueue = [];
/**
* 收集后置路由守卫中间件
*/
this.afterQueue = [];
this.registered = false;
}
/**
* 运行前置钩子中间件
*/
var _proto = LifecycleHook.prototype;
_proto.runBefore = function runBefore(to, from, next, middleware) {
var _this = this;
if (middleware.length === 0) {
next();
} else {
var fn = middleware.shift();
if (fn) {
fn(to, from, function (params) {
if (typeof params !== 'undefined') {
if (params === false) {
next();
} else {
next(params);
}
} else {
_this.runBefore(to, from, next, middleware);
}
});
}
}
}
/**
* 运行后置钩子中间件
*/
;
_proto.runAfter = function runAfter(to, from, next, middleware) {
var _this2 = this;
if (middleware.length === 0) {
next();
} else {
var fn = middleware.shift();
if (fn) {
fn(to, from, function (flag) {
if (typeof flag === 'undefined' || flag) {
_this2.runAfter(to, from, next, middleware);
}
});
}
}
}
/**
* 采集中间件
*/
;
_proto.use = function use() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
if (this.hook === 'beforeEach' || this.hook === 'beforeResolve') {
this.beforeQueue = this.beforeQueue.concat(args);
} else {
this.afterQueue = this.afterQueue.concat(args);
}
}
/**
* 注册路由守卫
*/
;
_proto.register = function register(router) {
var _this3 = this;
if (!this.registered) {
if (this.hook === 'beforeEach' || this.hook === 'beforeResolve') {
router[this.hook](function (to, from, next) {
_this3.runBefore(to, from, next, [].concat(_this3.beforeQueue));
});
} else {
router[this.hook](function (to, from) {
_this3.runAfter(to, from, function () {}, [].concat(_this3.afterQueue));
});
}
this.registered = true;
}
};
return LifecycleHook;
}();
var beforeEachHook = new LifecycleHook('beforeEach');
var beforeResolveHook = new LifecycleHook('beforeResolve');
var afterEachHook = new LifecycleHook('afterEach');
exports.afterEachHook = afterEachHook;
exports.beforeEachHook = beforeEachHook;
exports.beforeResolveHook = beforeResolveHook;
exports.default = LifecycleHook;
Object.defineProperty(exports, '__esModule', { value: true });
})));