nimble-ui
Version:
156 lines (152 loc) • 4.47 kB
JavaScript
import { mountService } from 'nimble-lib';
import Service from '../services';
export class RouterPreload extends Service {
name = 'RouterPreload';
defaultOption = {
routerOptions: {},
timeout: 2000 // 延时去加载
}
/**
* 定时器索引
*/
_timeout = null;
constructor(options) {
super(options);
let _that = this;
_that.setDefaultOptions(false, options);
}
/**
*停止加载
*
* @memberof Preload
*/
_stopLoad() {
let _that = this;
if (_that._timeout !== null) {
clearTimeout(_that._timeout);
}
}
/**
* 获取预加载的页面路径
* @param {string} routerPath 页面路径
* @param {Object} options 选项
* @returns {Promise}
*/
_getComponents(routerPath, options) {
let _options = this.getOptions(false, options || {});
return new Promise((resolve, reject) => {
if (routerPath) {
let paths = routerPath.split('/');
let routerItem = getRouterItem(_options.routerOptions || {}, paths);
try {
if (routerItem && routerItem.component instanceof Function) {
routerItem.component().then(resolve, reject);
} else {
resolve();
}
} catch (error) {
reject(error);
}
}
});
}
/**
*开始加载
*
* @param {*} route 当前路由
* @param {Object} options 选项
* @param {Object} pagelist 路由路径列表
* @returns {Promise}
* @memberof Preload
*/
load(route, options, pagelist) {
let _that = this;
let _options = _that.getOptions(false, options);
return new Promise((resolve, reject) => {
let _metaPreload = route && route.meta && route.meta.preload;
let _pagelist = pagelist || _metaPreload || [];
if (_pagelist && _pagelist.length > 0) {
_that._stopLoad();
_that._timeout = setTimeout(() => {
_that._timeout = null;
_pagelist.forEach((item) => { // 获取页面组件
pagelist.push(_that._getComponents(item, _options));
});
if (pagelist && pagelist.length > 0) { // 加载页面组件
Promise.all(pagelist)
.then(cb, reject);
} else {
cb([]);
}
}, _options.timeout);
} else {
cb([]);
}
/**
* 加载完成后的回调
* @param {Array} list 加载的列表
*/
function cb(list) {
if ((list && list.length) === (_pagelist && _pagelist.length)) {
if (_metaPreload) {
delete route.meta.preload;
}
}
resolve(list);
}
});
}
/**
* 安装
*
* @param {Vue} Vue Vue
* @param {Object} options 选项
* @memberof Service
* @returns {Object}
*/
install(Vue, options) {
let _that = this;
let name = mountService(Vue, _that);
_that.setDefaultOptions(true, (options && name && options[name]) || options);
return _that;
}
}
/**
* 获取路由项
*
* @param {*} obj 路由选项
* @param {*} list 页面路径字段列表
* @returns {object}
*/
function getRouterItem(obj, list) {
let _obj;
if (obj && list && list.length > 0) {
let key = list.shift();
if (key === '') {
list[0] = '/' + list[0];
_obj = getRouterItem(obj.routes, list);
} else {
_obj = obj.filter((item) => {
if (item.path === key) {
return item;
}
})[0];
if (list.length > 0) {
_obj = getRouterItem(_obj.children, list);
}
}
} else if (list && list.length > 0) {
_obj = undefined;
}
return _obj;
}
/**
* 实例化工厂
*
* @export
* @param {*} options 选项
* @returns {Preload}
*/
export default function preloadFactory(options) {
return new RouterPreload(options);
}