Skip to content
本页目录

router 路由

三种路由方式

  • hash 模式
  • history 模式
  • abstract 模式

hash 模式

依赖 hashchange 事件,此模式无需后端配合,浏览器监听 hash change 不会刷新页面

JS
// 监听hash变化
window.addEventListener('hashchange', (e) => {
    console.log(location.hash.slice(1)) // hash会以#开头,需要去除
})
// 监听hash变化
window.addEventListener('hashchange', (e) => {
    console.log(location.hash.slice(1)) // hash会以#开头,需要去除
})

history 模式

  • 依赖 history.pushStatehistory.replaceState 接口改变 url 地址
  • 监听用户使用浏览器的前进与回退触发的 popstate 事件
  • history.pushState()history.replaceState() 不会触发 popstate 事件,需要手动触发页面渲染;

所以我们既要监听 popstate 事件,又要监听用户点击事件去处理页面渲染,或者最直接的方案:重写 pushStatereplaceState 方法,使其支持自定义事件。

注意:该模式需要后端 nginx 配置路径重定向

nginx
location / {
    try_files $uri $uri/ /index.html;
}
location / {
    try_files $uri $uri/ /index.html;
}
JS
// popstate 事件监听无法被 pushState 与 replaceState 触发
window.addEventListener('popstate', (e) => {
    console.log(location.pathname)
})
// popstate 事件监听无法被 pushState 与 replaceState 触发
window.addEventListener('popstate', (e) => {
    console.log(location.pathname)
})

当然我们也可以重写 popstate 方法,来添加对其它的监听:

JS
let _wr = function(type) {
   let orig = history[type]
   return function() {
      let rv = orig.apply(this, arguments)
      let e = new Event(type)   // 这种也是 fastclick 的实现方式
      e.arguments = arguments
      window.dispatchEvent(e)
      return rv
   }
}

history.pushState = _wr('pushState')
history.replaceState = _wr('replaceState')


// 使用
btn.addEventListener('click', (e) => {
    history.pushState({state: 1}, null, './home')
})

window.addEventListener('popstate', urlChangeHandle)

function hashChangeHandle(e) {
    console.log(location.pathname)
}
let _wr = function(type) {
   let orig = history[type]
   return function() {
      let rv = orig.apply(this, arguments)
      let e = new Event(type)   // 这种也是 fastclick 的实现方式
      e.arguments = arguments
      window.dispatchEvent(e)
      return rv
   }
}

history.pushState = _wr('pushState')
history.replaceState = _wr('replaceState')


// 使用
btn.addEventListener('click', (e) => {
    history.pushState({state: 1}, null, './home')
})

window.addEventListener('popstate', urlChangeHandle)

function hashChangeHandle(e) {
    console.log(location.pathname)
}