[TOC]

使用vue-router时存在两种模式,hash和history。

  1. hash的实现是依赖浏览器的hashChange事件。
  2. history的实现,依赖h5中的pushState/popState实现。

    hash模式

    Vue-Router 默认为 hash 模式,基于浏览器的onhashchange事件,地址变化时,通过window.location.hash获取地址上的hash值;根据hash值匹配 routes 对象对应的组件内容。
    特点

  3. hash值存在 URL 中,携带#,hash值改变不会重载页面。

  4. hash改变会触发onhashchange事件,可被浏览器记录,从而实现浏览器的前进后退。
  5. hash传参基于url,传递复杂参数会有体积限制。
  6. 兼容性好,支持低版本浏览器和 IE 浏览器。

    <div class="main">
    <a href="#/home">home</a>
    <a href="#/detail">detail</a>
    <div id="content"><span>暂无内容</span></div>
    </div>
    <script>
    const routers = [{
     path: '/',
     component: `<span>暂无内容</span>`
    },
    {
    path: '/home',
    component: `<span>我是Home页面</span>`
    }, {
    path: '/detail',
    component: `<span>我是Detail页面</span>`
    }]
    
    function Router(routers) {
     console.log('执行')
     this.routersAction = {}
     // 初始化生成 routers
     routers.forEach((router) => {
       this.routersAction[router.path] = () => {
         document.getElementById("content").innerHTML = router.component;
       }
     })  
     this.updateView = function(e) {
       let hash = window.location.hash.slice(1) || '/'
       console.log('hash更新', hash, this.routersAction[hash])
       this.routersAction[hash] && this.routersAction[hash]()
     }
     // 路由加载触发视图更新
     window.addEventListener('load', this.updateView.bind(this))
     // 路由改变触发视图更新
     window.addEventListener('hashchange', this.updateView.bind(this))
    }
    // 实例化 hash 模式的 Router
    let router = new Router(routers) 
    </script>
    

    history模式

    基于HTML5新增的 pushState 和 replaceState 实现在不刷新的情况下,操作浏览器的历史纪录。前者是新增历史记录,后者是直接替换历史记录。
    特点

  7. URL 不携带#,利用 pushState 和 replaceState 完成 URL 跳转而无须重新加载页面。

  8. URL 更改会触发 http 请求。所以在服务端需增加一个覆盖所有情况的候选资源:若URL匹配不到任何静态资源,则应该返回同一个index.html。这个页面就是app依赖的页面。
    // nginx 服务端配置
    location / {
    try_files $uri $uri/ /index.html;
    }
    
    ```html
    home detail
    暂无内容

```