vue-router之history路由模式浅析

405 阅读1分钟

vue的路由模式有两种一种是hash模式还有一种history模式,那么他们有什么区别呢 ?


他们两个最大的区别就是在url中hash会带有#符号,但是在history模式中,#会被取消掉,在vue这类渐进式前端开发框架,为了构建 SPA(单页面应用),需要引入前端路由系统,这也就是 Vue-Router 存在的意义。前端路由的核心,就在于 —— 改变视图的同时不会向后端发出请求。

这里使用原生的js实现一下vue-router中的history模式

实现代码如下
我们先创建一个html文件在body中写入

    <div>
        <ul>
            <li><a href="/path1">path1</a></li>
            <li><a href="/path2">path2</a></li>
        </ul>
        <div id= "route-view"></div>
    </div>

在script标签中写入实现history模式的实现代码

所用到的 WEB API 接口

popstate介绍

DOMContentLoaded介绍

<script type="text/javascript">
        // 在这里我们需要对window进行事件监听
        //用到的DOMContentLoaded和popstate在上面有介绍
        window.addEventListener('DOMContentLoaded',Load)
        window.addEventListener('popstate', PopChange)
        var routeView = null
        function Load () {
            // 默认执行一次popstate的回调函数, 匹配一次页面组件
            routeView = document.getElementById("route-view")
            PopChange()
            // 获取所有a标签中所有带href的标签
            var aList = document.querySelectorAll("a[href]")
            aList.forEach(aNode => aNode.addEventListener('click', function(e){
                e.preventDefault() // 阻止a标签的默认事件
                // 手动修改浏览器的地址栏
                var href = aNode.getAttribute('href')
                // 使用history.pushState修改地址栏
                history.pushState(null, '', href)
                PopChange()

            }))
        }
        function PopChange () {
            console.log('localhost', location)
            switch (location.pathname) {
                case '/path1':
                     routeView.innerHtml = 'toPage1' 
                     return
                case '/path2': 
                    routeView.innerHtml = 'toPage2' 
                    return
                default: 
                    routeView.innerHtml = 'toPage1'
                    return
            }
        }
    </script>

这样我们就实现了简单的history路由模式,希望可以对学习vue-router的同学有一定的帮助