z-router-middleware-guard
Version:
a middleware guard plugin of vue-router 4.0
115 lines (97 loc) • 2.65 kB
JavaScript
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');
export default LifecycleHook;
export { afterEachHook, beforeEachHook, beforeResolveHook };