原生 js 完成一个前端路由 router

结果图:

《原生 js 完成一个前端路由 router》

项目地点:https://github.com/biaochenxuying/route

结果体验地点:

1. 滑动结果: https://biaochenxuying.github.io/route/index.html

2. 淡入淡出结果: https://biaochenxuying.github.io/route/index2.html

1. 需求

由于我司的 H 5 的项目是用原生 js 写的,要用到路由,然则如今好用的路由都是和某些框架绑定在一起的,比方 vue-router ,framework7 的路由;然则又没必要为了一个路由功用而到场一套框架,如今本身写一个轻量级的路由。

2. 完成道理

如今前端的路由完成平常有两种,一种是 Hash 路由,别的一种是 History 路由。

2.1 History 路由

History 接口许可操纵阅读器的曾经在标签页或许框架里接见的会话汗青纪录。

属性

  • History.length 是一个只读属性,返回当前 session 中的 history 个数,包含当前页面在内。举个例子,关于新开一个 tab 加载的页面当前属性返回值 1 。
  • History.state 返回一个示意汗青客栈顶部的状况的值。这是一种能够没必要守候 popstate 事宜而检察状况而的体式格局。

要领

  • History.back()

前去上一页, 用户可点击阅读器左上角的返回按钮模仿此要领. 等价于 history.go(-1).

Note: 当阅读器会话汗青纪录处于第一页时挪用此要领没有结果,而且也不会报错。

  • History.forward()

在阅读器汗青纪录里前去下一页,用户可点击阅读器左上角的行进按钮模仿此要领. 等价于 history.go(1).

Note: 当阅读器汗青栈处于最顶端时( 当前页面处于末了一页时 )挪用此要领没有结果也不报错。

  • History.go(n)

经由过程当前页面的相对位置从阅读器汗青纪录( 会话纪录 )加载页面。比方:参数为 -1的时刻为上一页,参数为 1 的时刻为下一页. 当整数参数超越界限时 ( 译者注:原文为 When integerDelta is out of bounds ),比方: 假如当前页为第一页,前面已没有页面了,我传参的值为 -1,那末这个要领没有任何结果也不会报错。挪用没有参数的 go() 要领或许不是整数的参数时也没有结果。( 这点与支撑字符串作为 url 参数的 IE 有点差别)。

  • history.pushState() 和 history.replaceState()

这两个 API 都吸收三个参数,分别是

a. 状况对象(state object) — 一个JavaScript对象,与用 pushState() 要领建立的新汗青纪录条目关联。不管什么时候用户导航到新建立的状况,popstate 事宜都邑被触发,而且事宜对象的state 属性都包含汗青纪录条目的状况对象的拷贝。

b. 题目(title) — FireFox 阅读器现在会疏忽该参数,虽然今后能够会用上。考虑到将来能够会对该要领举行修正,传一个空字符串会比较平安。或许,你也能够传入一个简短的题目,标明将要进入的状况。

c. 地点(URL) — 新的汗青纪录条目的地点。阅读器不会在挪用 pushState() 要领后加载该地点,但以后,能够会试图加载,比方用户重启阅读器。新的 URL 不一定是绝对途径;假如是相对途径,它将以当前 URL 为基准;传入的 URL 与当前 URL 应该是同源的,不然,pushState() 会抛出非常。该参数是可选的;不指定的话则为文档当前 URL。

雷同之处: 是两个 API 都邑操纵阅读器的汗青纪录,而不会引发页面的革新。

差别之处在于: pushState 会增添一条新的汗青纪录,而 replaceState 则会替代当前的汗青纪录。

例子:

原本的路由

 http://biaochenxuying.cn/

实行:

window.history.pushState(null, null, "http://biaochenxuying.cn/home");

路由变成了:

 http://biaochenxuying.cn/home

概况引见请看:MDN

2.2 Hash 路由

我们经常在 url 中看到 #,这个 # 有两种状况,一个是我们所谓的锚点,比方典范的回到顶部按钮道理、Github 上各个题目之间的跳转等,然则路由里的 # 不叫锚点,我们称之为 hash。

如今的前端主流框架的路由完成体式格局都邑采纳 Hash 路由,本项目采纳的也是。

当 hash 值发作转变的时刻,我们能够经由过程 hashchange 事宜监听到,从而在回调函数内里触发某些要领。

3. 代码完成

3.1 简朴版 – 单页面路由

先看个简朴版的 原生 js 模仿 Vue 路由切换。

《原生 js 完成一个前端路由 router》

道理

  • 监听 hashchange ,hash 转变的时刻,依据当前的 hash 婚配响应的 html 内容,然后用 innerHTML 把 html 内容放进 router-view 内里。

这个代码是网上的:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <meta name="author" content="">
    <title>原生模仿 Vue 路由切换</title>
    <style type="text/css">
        .router_box,
        #router-view {
            max-width: 1000px;
            margin: 50px auto;
            padding: 0 20px;
        }
        
        .router_box>a {
            padding: 0 10px;
            color: #42b983;
        }
    </style>
</head>

<body>
    <div class="router_box">
        <a href="/home" class="router">主页</a>
        <a href="/news" class="router">消息</a>
        <a href="/team" class="router">团队</a>
        <a href="/about" class="router">关于</a>
    </div>
    <div id="router-view"></div>
    <script type="text/javascript">
        function Vue(parameters) {
            let vue = {};
            vue.routes = parameters.routes || [];
            vue.init = function() {
                document.querySelectorAll(".router").forEach((item, index) => {
                    item.addEventListener("click", function(e) {
                        let event = e || window.event;
                        event.preventDefault();
                        window.location.hash = this.getAttribute("href");
                    }, false);
                });

                window.addEventListener("hashchange", () => {
                    vue.routerChange();
                });

                vue.routerChange();
            };
            vue.routerChange = () => {
                let nowHash = window.location.hash;
                let index = vue.routes.findIndex((item, index) => {
                    return nowHash == ('#' + item.path);
                });
                if (index >= 0) {
                    document.querySelector("#router-view").innerHTML = vue.routes[index].component;
                } else {
                    let defaultIndex = vue.routes.findIndex((item, index) => {
                        return item.path == '*';
                    });
                    if (defaultIndex >= 0) {
                        window.location.hash = vue.routes[defaultIndex].redirect;
                    }
                }
            };

            vue.init();
        }

        new Vue({
            routes: [{
                path: '/home',
                component: "<h1>主页</h1><a href='https://github.com/biaochenxuying'>https://github.com/biaochenxuying</a>"
            }, {
                path: '/news',
                component: "<h1>消息</h1><a href='http://biaochenxuying.cn/main.html'>http://biaochenxuying.cn/main.html</a>"
            }, {
                path: '/team',
                component: '<h1>团队</h1><h4>全栈修炼</h4>'
            }, {
                path: '/about',
                component: '<h1>关于</h1><h4>关注民众号:BiaoChenXuYing</h4><p>分享 WEB 全栈开辟等相干的手艺文章,热门资本,全栈程序员的生长之路。</p>'
            }, {
                path: '*',
                redirect: '/home'
            }]
        });
    </script>
</body>

</html>

3.2 庞杂版 – 内联页面版,带缓存功用

起首前端用 js 完成路由的缓存功用是很难的,但像 vue-router 那种还好,由于有 vue 框架和假造 dom 的手艺,能够保留当前页面的数据。

要做缓存功用,起首要知道阅读器的 行进、革新、回退 这三个操纵。

然则阅读器中重要有这几个限定:

  • 没有供应监听行进退却的事宜
  • 不许可开辟者读取阅读纪录
  • 用户能够手动输入地点,或运用阅读器供应的行进退却来转变 url

所以要自定义路由,解决方案是本身保护一份路由汗青的纪录,存在一个数组内里,从而辨别 行进、革新、回退。

  • url 存在于阅读纪录中即为退却,退却时,把当前路由背面的阅读纪录删除。
  • url 不存在于阅读纪录中即为行进,行进时,往数组内里 push 当前的路由。
  • url 在阅读纪录的末尾即为革新,革新时,不对路由数组做任何操纵。

别的,运用的路由途径中能够许可雷同的路由涌现屡次(比方 A -> B -> A),所以给每一个路由增加一个 key 值来辨别雷同路由的差别实例。

这个阅读纪录须要存储在 sessionStorage 中,如许用户革新后阅读纪录也能够恢复。

3.2.1 route.js
3.2.1.1 跳转要领 linkTo

像 vue-router 那样,供应了一个 router-link 组件来导航,而我这个框架也供应了一个 linkTo 的要领。

        // 天生差别的 key 
        function genKey() {
            var t = 'xxxxxxxx'
            return t.replace(/[xy]/g, function(c) {
                var r = Math.random() * 16 | 0
                var v = c === 'x' ? r : (r & 0x3 | 0x8)
                return v.toString(16)
            })
        }

        // 初始化跳转要领
        window.linkTo = function(path) {
                if (path.indexOf("?") !== -1) {
                    window.location.hash = path + '&key=' + genKey()
                } else {
                    window.location.hash = path + '?key=' + genKey()
                }
        }

用法:

//1. 直接用 a 标签
<a href='#/list' >列表1</a>

//2. 标签加 js 挪用要领
<div onclick='linkTo(\"#/home\")'>首页</div>

// 3. js 挪用触发
linkTo("#/list")
3.2.1.2 组织函数 Router

定义好要用到的变量

function Router() {
        this.routes = {}; //保留注册的一切路由
        this.beforeFun = null; //切换前
        this.afterFun = null; // 切换后
        this.routerViewId = "#routerView"; // 路由挂载点 
        this.redirectRoute = null; // 路由重定向的 hash
        this.stackPages = true; // 多级页面缓存
        this.routerMap = []; // 路由遍历
        this.historyFlag = '' // 路由状况,行进,回退,革新
        this.history = []; // 路由汗青
        this.animationName = "slide" // 页面切换时的动画
    }
3.2.1.3 完成路由功用

包含:初始化、注册路由、汗青纪录、切换页面、切换页面的动画、切换之前的钩子、切换以后的钩子、转动位置的处置惩罚,缓存。

Router.prototype = {
        init: function(config) {
            var self = this;
            this.routerMap = config ? config.routes : this.routerMap
            this.routerViewId = config ? config.routerViewId : this.routerViewId
            this.stackPages = config ? config.stackPages : this.stackPages
            var name = document.querySelector('#routerView').getAttribute('data-animationName')
            if (name) {
                this.animationName = name
            }
            this.animationName = config ? config.animationName : this.animationName

            if (!this.routerMap.length) {
                var selector = this.routerViewId + " .page"
                var pages = document.querySelectorAll(selector)
                for (var i = 0; i < pages.length; i++) {
                    var page = pages[i];
                    var hash = page.getAttribute('data-hash')
                    var name = hash.substr(1)
                    var item = {
                        path: hash,
                        name: name,
                        callback: util.closure(name)
                    }
                    this.routerMap.push(item)
                }
            }

            this.map()

            // 初始化跳转要领
            window.linkTo = function(path) {
                console.log('path :', path)
                if (path.indexOf("?") !== -1) {
                    window.location.hash = path + '&key=' + util.genKey()
                } else {
                    window.location.hash = path + '?key=' + util.genKey()
                }
            }

            //页面初次加载 婚配路由
            window.addEventListener('load', function(event) {
                // console.log('load', event);
                self.historyChange(event)
            }, false)

            //路由切换
            window.addEventListener('hashchange', function(event) {
                // console.log('hashchange', event);
                self.historyChange(event)
            }, false)

        },
        // 路由汗青纪录变化
        historyChange: function(event) {
            var currentHash = util.getParamsUrl();
            var nameStr = "router-" + (this.routerViewId) + "-history"
            this.history = window.sessionStorage[nameStr] ? JSON.parse(window.sessionStorage[nameStr]) : []

            var back = false,
                refresh = false,
                forward = false,
                index = 0,
                len = this.history.length;

            for (var i = 0; i < len; i++) {
                var h = this.history[i];
                if (h.hash === currentHash.path && h.key === currentHash.query.key) {
                    index = i
                    if (i === len - 1) {
                        refresh = true
                    } else {
                        back = true
                    }
                    break;
                } else {
                    forward = true
                }
            }
            if (back) {
                this.historyFlag = 'back'
                this.history.length = index + 1
            } else if (refresh) {
                this.historyFlag = 'refresh'
            } else {
                this.historyFlag = 'forward'
                var item = {
                    key: currentHash.query.key,
                    hash: currentHash.path,
                    query: currentHash.query
                }
                this.history.push(item)
            }
            console.log('historyFlag :', this.historyFlag)
                // console.log('history :', this.history)
            if (!this.stackPages) {
                this.historyFlag = 'forward'
            }
            window.sessionStorage[nameStr] = JSON.stringify(this.history)
            this.urlChange()
        },
        // 切换页面
        changeView: function(currentHash) {
            var pages = document.getElementsByClassName('page')
            var previousPage = document.getElementsByClassName('current')[0]
            var currentPage = null
            var currHash = null
            for (var i = 0; i < pages.length; i++) {
                var page = pages[i];
                var hash = page.getAttribute('data-hash')
                page.setAttribute('class', "page")
                if (hash === currentHash.path) {
                    currHash = hash
                    currentPage = page
                }
            }
            var enterName = 'enter-' + this.animationName
            var leaveName = 'leave-' + this.animationName
            if (this.historyFlag === 'back') {
                util.addClass(currentPage, 'current')
                if (previousPage) {
                    util.addClass(previousPage, leaveName)
                }
                setTimeout(function() {
                    if (previousPage) {
                        util.removeClass(previousPage, leaveName)
                    }
                }, 250);
            } else if (this.historyFlag === 'forward' || this.historyFlag === 'refresh') {
                if (previousPage) {
                    util.addClass(previousPage, "current")
                }
                util.addClass(currentPage, enterName)
                setTimeout(function() {
                    if (previousPage) {
                        util.removeClass(previousPage, "current")
                    }
                    util.removeClass(currentPage, enterName)
                    util.addClass(currentPage, 'current')
                }, 350);
                // 行进和革新都实行回调 与 初始转动位置为 0
                currentPage.scrollTop = 0
                this.routes[currHash].callback ? this.routes[currHash].callback(currentHash) : null
            }
            this.afterFun ? this.afterFun(currentHash) : null
        },
        //路由处置惩罚
        urlChange: function() {
            var currentHash = util.getParamsUrl();
            if (this.routes[currentHash.path]) {
                var self = this;
                if (this.beforeFun) {
                    this.beforeFun({
                        to: {
                            path: currentHash.path,
                            query: currentHash.query
                        },
                        next: function() {
                            self.changeView(currentHash)
                        }
                    })
                } else {
                    this.changeView(currentHash)
                }
            } else {
                //不存在的地点,重定向到默许页面
                location.hash = this.redirectRoute
            }
        },
        //路由注册
        map: function() {
            for (var i = 0; i < this.routerMap.length; i++) {
                var route = this.routerMap[i]
                if (route.name === "redirect") {
                    this.redirectRoute = route.path
                } else {
                    this.redirectRoute = this.routerMap[0].path
                }
                var newPath = route.path
                var path = newPath.replace(/\s*/g, ""); //过滤空格
                this.routes[path] = {
                    callback: route.callback, //回调
                }
            }
        },
        //切换之前的钩子
        beforeEach: function(callback) {
            if (Object.prototype.toString.call(callback) === '[object Function]') {
                this.beforeFun = callback;
            } else {
                console.trace('路由切换前钩子函数不正确')
            }
        },
        //切换胜利以后的钩子
        afterEach: function(callback) {
            if (Object.prototype.toString.call(callback) === '[object Function]') {
                this.afterFun = callback;
            } else {
                console.trace('路由切换后回调函数不正确')
            }
        }
    }
3.2.1.4 注册到 Router 到 window 全局
    window.Router = Router;
    window.router = new Router();

完全代码:https://github.com/biaochenxu…

3.2.2 运用要领
3.2.2.1 js 定义法
  • callback 是切换页面后,实行的回调
<script type="text/javascript">
        var config = {
            routerViewId: 'routerView', // 路由切换的挂载点 id
            stackPages: true, // 多级页面缓存
            animationName: "slide", // 切换页面时的动画
            routes: [{
                path: "/home",
                name: "home",
                callback: function(route) {
                    console.log('home:', route)
                    var str = "<div><a class='back' onclick='window.history.go(-1)'>返回</a></div> <h2>首页</h2> <input type='text'> <div><a href='javascript:void(0);' onclick='linkTo(\"#/list\")'>列表</a></div><div class='height'>内容占位</div>"
                    document.querySelector("#home").innerHTML = str
                }
            }, {
                path: "/list",
                name: "list",
                callback: function(route) {
                    console.log('list:', route)
                    var str = "<div><a class='back' onclick='window.history.go(-1)'>返回</a></div> <h2>列表</h2> <input type='text'> <div><a href='javascript:void(0);' onclick='linkTo(\"#/detail\")'>概况</a></div>"
                    document.querySelector("#list").innerHTML = str
                }
            }, {
                path: "/detail",
                name: "detail",
                callback: function(route) {
                    console.log('detail:', route)
                    var str = "<div><a class='back' onclick='window.history.go(-1)'>返回</a></div> <h2>概况</h2> <input type='text'> <div><a href='javascript:void(0);' onclick='linkTo(\"#/detail2\")'>概况 2</a></div><div class='height'>内容占位</div>"
                    document.querySelector("#detail").innerHTML = str
                }
            }, {
                path: "/detail2",
                name: "detail2",
                callback: function(route) {
                    console.log('detail2:', route)
                    var str = "<div><a class='back' onclick='window.history.go(-1)'>返回</a></div> <h2>概况 2</h2> <input type='text'> <div><a href='javascript:void(0);' onclick='linkTo(\"#/home\")'>首页</a></div>"
                    document.querySelector("#detail2").innerHTML = str
                }
            }]
        }

        //初始化路由
        router.init(config)
        router.beforeEach(function(transition) {
            console.log('切换之 前 dosomething', transition)
            setTimeout(function() {
                //模仿切换之前耽误,比方说做个异步登录信息考证
                transition.next()
            }, 100)
        })
        router.afterEach(function(transition) {
            console.log("切换之 后 dosomething", transition)
        })
    </script>
3.2.2.2 html 加 <script> 定义法
  • id=”routerView” :路由切换时,页面的视图窗口
  • data-animationName=”slide”:切换时的动画,现在有 slide 和 fade。
  • class=”page”: 切换的页面
  • data-hash=”/home”:home 是切换路由时实行的回调要领
  • window.home : 回调要领,名字要与 data-hash 的名字雷同
<div id="routerView" data-animationName="slide">
        <div class="page" data-hash="/home">
            <div class="page-content">
                <div id="home"></div>
                <script type="text/javascript">
                    window.home = function(route) {
                        console.log('home:', route)
                            // var str = "<div><a class='back' onclick='window.history.go(-1)'>返回</a></div> <h2>首页</h2> <input type='text'> <div><a href='#/list' >列表1</div></div><div class='height'>内容占位</div>"
                        var str = "<div><a class='back' onclick='window.history.go(-1)'>返回</a></div> <h2>首页</h2> <input type='text'> <div><div href='javascript:void(0);' onclick='linkTo(\"#/list\")'>列表</div></div><div class='height'>内容占位</div>"
                        document.querySelector("#home").innerHTML = str
                    }
                </script>
            </div>
        </div>
        <div class="page" data-hash="/list">
            <div class="page-content">
                <div id="list"></div>
                <div style="height: 700px;border: solid 1px red;background-color: #eee;margin-top: 20px;">内容占位</div>

                <script type="text/javascript">
                    window.list = function(route) {
                        console.log('list:', route)
                        var str = "<div><a class='back' onclick='window.history.go(-1)'>返回</a></div> <h2>列表</h2> <input type='text'> <div><a href='javascript:void(0);' onclick='linkTo(\"#/detail\")'>概况</a></div>"
                        document.querySelector("#list").innerHTML = str
                    }
                </script>
            </div>
        </div>
        <div class="page" data-hash="/detail">
            <div class="page-content">
                <div id="detail"></div>
                <script type="text/javascript">
                    window.detail = function(route) {
                        console.log('detail:', route)
                        var str = "<div><a class='back' onclick='window.history.go(-1)'>返回</a></div> <h2>概况</h2> <input type='text'> <div><a href='javascript:void(0);' onclick='linkTo(\"#/detail2\")'>概况 2</a></div><div class='height'>内容占位</div>"
                        document.querySelector("#detail").innerHTML = str
                    }
                </script>
            </div>
        </div>
        <div class="page" data-hash="/detail2">
            <div class="page-content">
                <div id="detail2"></div>
                <div style="height: 700px;border: solid 1px red;background-color: pink;margin-top: 20px;">内容占位</div>

                <script type="text/javascript">
                    window.detail2 = function(route) {
                        console.log('detail2:', route)
                        var str = "<div><a class='back' onclick='window.history.go(-1)'>返回</a></div> <h2>概况 2</h2> <input type='text'> <div><a href='javascript:void(0);' onclick='linkTo(\"#/home\")'>首页</a></div>"
                        document.querySelector("#detail2").innerHTML = str
                    }
                </script>
            </div>
        </div>
    </div>
    <script type="text/javascript" src="./js/route.js"></script>
    <script type="text/javascript">
        router.init()
        router.beforeEach(function(transition) {
            console.log('切换之 前 dosomething', transition)
            setTimeout(function() {
                //模仿切换之前耽误,比方说做个异步登录信息考证
                transition.next()
            }, 100)
        })
        router.afterEach(function(transition) {
            console.log("切换之 后 dosomething", transition)
        })
    </script>

参考项目:https://github.com/kliuj/spa-…

5. 末了

项目地点:https://github.com/biaochenxuying/route

博客常更地点1 :https://github.com/biaochenxuying/blog

博客常更地点2 :http://biaochenxuying.cn/main.html

足足一个多月没有更新文章了,由于项目太紧,加班加班啊,趁着在家有空,赶忙写下这篇干货,以免忘记了,愿望对人人有所协助。

假如您以为这篇文章不错或许对你有所协助,请点个赞,感谢。

《原生 js 完成一个前端路由 router》

全栈修炼 有兴致的朋侪能够扫下方二维码关注我的民众号

我会不定期更新有价值的内容,历久运营。

关注民众号并复兴 福利 可领取免费进修材料,福利概况请猛戳: Python、Java、Linux、Go、node、vue、react、javaScript

《原生 js 完成一个前端路由 router》

    原文作者:夜尽天明
    原文地址: https://segmentfault.com/a/1190000018058416
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞