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'))
        })
  • 相关阅读:
    centos 用户管理
    rsync 实验
    文件共享和传输
    PAT 1109 Group Photo
    PAT 1108 Finding Average
    PAT 1107 Social Clusters
    PAT 1106 Lowest Price in Supply Chain
    PAT 1105 Spiral Matrix
    PAT 1104 Sum of Number Segments
    PAT 1103 Integer Factorization
  • 原文地址:https://www.cnblogs.com/littleboyck/p/13607016.html
Copyright © 2011-2022 走看看