美文网首页前端学习园地Web前端之路
spa路由简单实现代码解析(梁王的代码解剖室)

spa路由简单实现代码解析(梁王的代码解剖室)

作者: 梁王io | 来源:发表于2017-08-27 01:11 被阅读192次

    前言

    本文假设读者使用过或者了解什么是SPA

    SPA路由简单实现

    代码(被解析项目地址)

    为了避免误会,代码不是我写的,我只是解析源码。
    spa-routers
    demo演示: demo

    解析

    解析分3个部分,hash路由,路由规则注册,路由同异步加载

    hash路由

    用过vue之类的框架应该都知道什么是hash,这里说的是url的hash不是数据结构里面的东西。
    类似这种http://www.example.com/index.html#print

    单页应用当hash变换的时候,切换不同的界面。而浏览器提供了一个事件hashchange

    function changePart(event) {
        alert('your hash changed');
        console.log(event);
    }
    window.onhashchange = changePart;
    

    读者可以自行在控制台试一下然后改变hash看看。

    在项目代码中,在初始化spaRouters的时候会监听事件

    spaRouters.prototype={
        init:function(){
            var self = this;
            //页面加载匹配路由
            window.addEventListener('load',function(){
                self.urlChange()
            })
            //路由切换
            window.addEventListener('hashchange',function(){
                self.urlChange()
            })
            ...
        },
        ...
    }
    

    现在我们来看看urlChange方法,方法在spaRouters的原型里面

        ...
        urlChange:function(){
            var currentHash = util.getParamsUrl();
            if(this.routers[currentHash.path]){
                this.refresh(currentHash)
            }else{
                //不存在的地址重定向到首页
                location.hash = '/index'
            }
        },
        refresh:function(currentHash){
            var self = this;
            // 提供导航钩子
            if(self.beforeFun){
                // 这里还可以像vue一样还提供from
                self.beforeFun({
                    to:{
                        path:currentHash.path,
                        query:currentHash.query
                    },
                    // 关于next我明天会补充一下
                    next:function(){
                        self.routers[currentHash.path].callback.call(self,currentHash)
                    }
                })
            }else{
                self.routers[currentHash.path].callback.call(self,currentHash)
            }
        },
        ...
    

    hash变更后,看routers里面有没有hash对应的路由规则(这里直接用的下标,其实想做得更好可以使用模板,还有用正则来匹配,像vue路由就有类似/users/:id这种)。

    如果有匹配的话调用refresh,refresh这里还提供了导航钩子beforeFun(通过spaRouters原型提供的beforeEach还有afterEach的方法设置),其中的next我后面会再扩展一下。

    路由规则注册

    刚刚讲完了hash变化后程序的逻辑,现在我们来看看怎么注册路由规则。
    同样是spaRouters的原型里面

        //单层路由注册
        ...
        map:function(path,callback){
            path = path.replace(/\s*/g,"");//过滤空格
            if(callback && Object.prototype.toString.call(callback) === '[object Function]' ){
                this.routers[path] ={
                    callback:callback,//回调
                    fn:null //存储异步文件状态
                }
            }else{
                console.trace('注册'+path+'地址需要提供正确的的注册回调')
            }
        },
        ...
    

    原型中的map方法注册路由,并提供一个回调,这个回调也就是上面hashchange的时候会调用的内容,一般是进行同异步加载js。下面是项目内的测试调用

        ...
        spaRouters.map('/index',function(transition){
          spaRouters.asyncFun('js/index.js',transition)
        })
        spaRouters.map('/list',function(transition){
          spaRouters.asyncFun('js/list.js',transition)
        })
        spaRouters.map('/detail',function(transition){
          spaRouters.asyncFun('js/detail.js',transition)
        })
        spaRouters.map('/detail2',function(transition){
          spaRouters.syncFun(function(transition){
            document.getElementById("content").innerHTML = '<p>当前同步渲染详情页' + JSON.stringify(transition) +'</p>'
          },transition)
        })
        ...
    

    其中的syncFun和asyncFun我在第三部分讲
    之前也说了,这里可以优化一下使用模板正则匹配(当然使用正则之后又有注册顺序的问题)

    同异步加载

    同样是在spaRouters的原型中的两个方法

        ...
        //路由异步懒加载js文件
        asyncFun:function(file,transition){
           var self = this;
           if(self.routers[transition.path].fn){
                self.afterFun && self.afterFun(transition)
                self.routers[transition.path].fn(transition)
           }else{
               console.log("开始异步下载js文件"+file)
               var _body= document.getElementsByTagName('body')[0];
               var scriptEle= document.createElement('script');
               scriptEle.type= 'text/javascript';
               scriptEle.src= file;
               scriptEle.async = true;
               SPA_RESOLVE_INIT = null;
               scriptEle.onload= function(){
                   console.log('下载'+file+'完成')
                   self.afterFun && self.afterFun(transition)
                   self.routers[transition.path].fn = SPA_RESOLVE_INIT;
                   self.routers[transition.path].fn(transition)
               }
               _body.appendChild(scriptEle);
           }
        },
        //同步操作
        syncFun:function(callback,transition){
            // 路由切换后的回调
            this.afterFun && this.afterFun(transition)
            // 路由注册时设置的回调
            callback && callback(transition)
        }
        ...
    

    同步简单一点我们先说同步吧,map注册路由的第二个参数是callback,在hash发发生变化的时候refresh里面调用的回调。基本上是直接调用回调就行了

    然后我们来看看异步的部分。异步部分懒加载js文件。
    这里注意一下一开始有个判断

        if(self.routers[transition.path].fn){
            self.afterFun && self.afterFun(transition)
            self.routers[transition.path].fn(transition)
        }else{
        ...
    

    这个fn算是一个标示位,异步加载的js文件里面会设置一个叫SPA_RESOLVE_INIT的变量。

       SPA_RESOLVE_INIT = null;
       scriptEle.onload= function(){
           console.log('下载'+file+'完成')
           self.afterFun && self.afterFun(transition)
           self.routers[transition.path].fn = SPA_RESOLVE_INIT;
           self.routers[transition.path].fn(transition)
       }
    

    而对应的js文件内容可能是

    SPA_RESOLVE_INIT = function(transition) { 
        document.getElementById("content").innerHTML = '<p style="color:red;">当前异步渲染详情页'+ JSON.stringify(transition) +'</p>'
        console.log("首页回调" + JSON.stringify(transition))
    }
    

    所以可以通过fn判断当前路由js文件已经下载下来了就不需要再次下载了,直接调用。

    后记

    本文大致解析了一下简单SPA的路由部分,所解析代码也是比较简单的,也有很多可以改进的地方,读者有什么好的改进方案可以在评论区沟通交流一下。

    相关文章

      网友评论

      • 一个小小的蚂蚁:请问hash路由时www.baidu.com/#/a和www.baidu.com#/a的区别?就是#号前面写斜杠和不写斜杠的区别?
        梁王io:我觉得没什么区别,发起的请求都是http://www.baidu.com/ hash也都是 /a

      本文标题:spa路由简单实现代码解析(梁王的代码解剖室)

      本文链接:https://www.haomeiwen.com/subject/lttbdxtx.html