zoukankan      html  css  js  c++  java
  • 原生js实现一个路由hash router

    <div><a r-link="#/home">首页</a></div>
    <div><a r-link="#/button">按钮组件</a></div>
    <div><a r-link="#/form">表单组件</a></div>
    
    <div id="app"></div>
        class Router{
                constructor(){
                    //缓存route数据信息
                    this.routes = {};
                    this.ready();
                }
    
                static isDOM(el){
                    el = Array.from(el);
                    if(el.length == 0){return false;}
                    for(let i = 0,len=el.length; i<len; i++){
                        if(el[i].nodeType != (Node.ELEMENT_NODE||Node.DOCUMENT_NODE)){
                            return false;
                        }
                    }
                    return true;
                }
    
                static getEl(selector){
                    if(selector.nodeType != (Node.ELEMENT_NODE||Node.DOCUMENT_NODE)){
                        if(/^#[^#s]+$/.test(selector)){
                            selector = document.querySelector(selector)
                        }else{
                            selector = document.querySelectorAll(selector)
                        }
                    }
                    return selector;
                }
    
                static evtListener(el,event,handle){
                    el = Router.isDOM(el) ? [...el] : [el];
                    el.forEach(el=>el.addEventListener(event,handle));
                }
    
                static removeListener(el,event,handle){
                    el = Router.isDOM(el) ? [...el] : [el];
                    el.forEach(el=>el.removeEventListener(event,handle));
                }
    
                static xhr(options){
                    
                }
    
                static isHash(val){
                    return /^#[^s]+$/.test(val)
                }
    
                static setTitle(htmlString){
                    let result = /<title>([wW]*)</title>/.exec(htmlString) 
                    ,title = result ? result[1] : htmlString;
                    //,matches = document.querySelectorAll('title')[0].textContent.match(/^{{([^{}]+)}}$/);
                    document.querySelectorAll('title')[0].textContent = title
                }
    
                //收集routes
                route(path,callback){
                    this.routes[path] = callback ? callback : function(){};
                }
    
                //跳转至指定path
                go(path){
                    location.hash != path && (location.hash = path)
                }
    
                init(firstPath){
                    location.hash && (firstPath = location.hash)
                    //加载默认的内容页
                    Router.isHash(firstPath) && (location.hash = firstPath) && this.routes[firstPath] && this.routes[firstPath].call(this)
                }
                
                //监听hashchange
                listenerHashchange(){
                    Router.evtListener(window,'hashchange',()=>{
                        let path = location.hash;
                        this.routes[path] && this.routes[path].call(this)
                    });
                }
    
                //初始化
                ready(){
                    this.listenerHashchange();
                }
            }

     使用方式

        const router = new Router()
        //1、注册routes依赖
        router.route("#/home",function(){
            Router.setTitle("首页")
            document.getElementById('content').innerHTML = '欢迎来到首页'
        })
        router.route("#/button",function(){
            $.ajax({
                type:'get'
                ,url:'../component/button.html'
            }).then(function(html){
                Router.setTitle(html)
                document.getElementById('content').innerHTML = html;
            })
        })
        router.route("#/form",function(){
            $.ajax({
                type:'get'
                ,url:'../component/element.html'
            }).then(function(html){
                Router.setTitle(html)
                document.getElementById('content').innerHTML = html;
            })
        })
        //2、初始化默认页
        router.init('#/home')
        //3、点击事件
        Router.evtListener(document.querySelectorAll('[r-link]'),'click',function (e) {
            router.go(this.getAttribute('r-link'))
        })
  • 相关阅读:
    烯烃(olefin) 题解
    二分图的考验 题解
    树上的好题
    [SDOI2013]直径 题解
    [ZJOI2010]数字计数 题解
    神在夏至祭降下了神谕 题解
    洛谷 P4198 楼房重建 题解
    [HAOI2010]软件安装 题解
    [POI2011]ROT-Tree Rotations 题解
    可并堆之左偏树浅谈
  • 原文地址:https://www.cnblogs.com/littleboyck/p/13607016.html
Copyright © 2011-2022 走看看