基于jQuery load实现单页面路由嵌套管理及缓存
1.用法
- 主页面配置路由
- 根页面为div添加id = 'root’作为根路由容器渲染一级路由
- 嵌套路由容器:为div添加router-view类作为容器存放子路由
2.代码
(function (win) {
let Router = function (routes) {
this.recentHashpath = ''
this.query = Object.create(null)
this.routes = routes
window.addEventListener("hashchange", function (e) {
this.analysis(location.hash)
}.bind(this));
this.analysis(location.hash)
}
Router.prototype.analysis = function(hashpath){
this.query = Router.generateQuery(hashpath)
let nowpathArr = Router.generateHashPath(hashpath)
let oldpathArr = Router.generateHashPath(this.recentHashpath)
let index = 0
nowpathArr.forEach((path, i) => {
if (oldpathArr[0] != '/' && oldpathArr[i] && oldpathArr[i] === path) {
index++
}
else return
});
forEachRoutes(this.routes, nowpathArr, 1, index)
this.recentHashpath = hashpath
function forEachRoutes(routes, pathArr, i, index) {
routes.forEach((route) => {
let el = '#root'
for (let j = 1; j < i; j++) {
el += ' div.router-view'
}
if (route['path'] == pathArr[0]) {
if (i > index)
route['page'].mount($(el)).then(() => {
if (route['children'])
forEachRoutes(route['children'], pathArr.slice(1), i + 1, index)
})
else if (route['children'])
forEachRoutes(route['children'], pathArr.slice(1), i + 1, index)
}
if (pathArr.length === 0) {
$(el).html('')
}
});
}
}
Router.prototype.to = function(path){
location.hash = path
}
Router.prototype.back = ()=> {
history.back()
}
Router.prototype.forword = ()=> {
history.forward()
}
Router.prototype.replace = function(path){
location.replace('/#' + path)
}
Router.generateHashPath = function(hashpath = '#/'){
if (hashpath == '/' || hashpath == '' || hashpath == '/#')
hashpath = '#/'
let hashpathStr = hashpath.split('?')[0]
return hashpathStr.slice(2).split('/').map(i => {
return '/' + i
})
}
Router.generateQuery = function(hashpath = '#/'){
let query = Object.create(null)
if (hashpath == '/' || hashpath == '' || hashpath == '/#')
hashpath = '#/'
let queryStr = hashpath.split('?')[1]
if (queryStr) {
queryStr.split('&').forEach((i) => {
let line = i.split('=')
if (!line[1]) line[1] = ''
query[line[0]] = line[1]
})
}
return query
}
win.Router = Router
})(window);
(function (win) {
let Page = function(src){
this.src = src
this.domtext = null
}
Page.prototype.mount = function(el){
return new Promise((resolve, reject) => {
if (!this.domtext) {
$('.progress').removeClass('hidden')
el.load(this.src, (response, status) => {
if (status != 'success') return
this.domtext = response
$('.progress').addClass('hidden')
resolve()
})
}
else {
el.html(this.domtext)
resolve()
}
})
}
win.Page = Page
})(window)
let router = new Router([
{
path: '/',
page: new Page('./page/def.htm'),
},
{
path: '/home',
page: new Page('./page/home/home.htm'),
children: [
{
path: '/about',
page: new Page('./page/home/about.htm')
},
]
}
])