基于jQuery load实现单页面路由嵌套管理及缓存

基于jQuery load实现单页面路由嵌套管理及缓存

1.用法

  • 主页面配置路由
  • 根页面为div添加id = 'root’作为根路由容器渲染一级路由
  • 嵌套路由容器:为div添加router-view类作为容器存放子路由

2.代码

//生成Router,路由控制类
(function (win) {
    let Router = function (routes) {
        //记录当前的路由位置 
        this.recentHashpath = ''
        this.query = Object.create(null)
        this.routes = routes
        //监听hash路由变化
        window.addEventListener("hashchange", function (e) {
            this.analysis(location.hash)
        }.bind(this));
        this.analysis(location.hash)
    }
    Router.prototype.analysis = function(hashpath){
        //解析query
        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'])//层级小于index,不渲染直接跳到下一层级
                        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')
            },
         ]
    }
])
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值