单页面路由跳转之hash模式

hash模式

hash模式主要通过监听URL地址的哈希值的变化来实现页面更新

function routeHandle() {
  let appElm = document.querySelector('#app')
  let hash = window.location.hash.slice(1)

  switch (hash) {
    case '':
    case '/':
    case '/home':
      appElm.innerHTML = `
        

Home

`
bindEvent() break case '/list': appElm.innerHTML = `

List

`
bindEvent() break default: appElm.innerHTML = `

404

`
break } } window.addEventListener('hashchange', routeHandle, false)

完整代码

<body>
  <div id="app">div>
body>
function routeHandle() {
  let appElm = document.querySelector('#app')
  let hash = window.location.hash.slice(1)

  switch (hash) {
    case '':
    case '/':
    case '/home':
      appElm.innerHTML = `
        

Home

`
bindEvent() break case '/list': appElm.innerHTML = `

List

`
bindEvent() break default: appElm.innerHTML = `

404

`
break } } function toListBtnHandle() { window.location.hash = '#/list' } function toHomeBtnHandle() { window.location.hash = '#/' } function bindEvent() { let toListBtnElm = document.querySelector('#toListBtn') let toHomeBtnElm = document.querySelector('#toHomeBtn') toListBtnElm && toListBtnElm.addEventListener('click', toListBtnHandle, false) toHomeBtnElm && toHomeBtnElm.addEventListener('click', toHomeBtnHandle, false) } window.addEventListener('hashchange', routeHandle, false) ;(() => { routeHandle() })()

你可能感兴趣的:(前端,javascript)