两种前端路由的原理之hash&history

  • 路由的分类
    • hash
    • html5 api history
  • 为什么使用路由?
    • SPA:single page application
    • 页面的地址栏跳转

index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>router</title>
</head>
<body>
  <ul>
    <li to="/movie">电影</li>
    <li to="/theater">影院</li>
  </ul>
  <div id="view"></div>
  <div>
    <button id="back">back</button>
    <button id="go">go</button>
  </div>
  <script src="./history.js"></script>
</body>
</html>

hash.js

const view = document.querySelector('#view')

const Movie = () => {
  view.innerHTML = `
    <div>电影列表</div>
  `
}
const Theater = () => {
  view.innerHTML = `
    <div>影院列表</div>
  `
}

window.addEventListener('load', Movie, false)

window.addEventListener('hashchange', () => {
  let hash = location.hash
  switch(hash) {
    case '#/movie':
      Movie()
      break;
    case '#/theater':
      Theater()
      break;
    default:
      Movie()
  }
}, false)

history.js

const history = window.history

const lis = document.querySelectorAll('li')

const Movie = () => {
  view.innerHTML = `
    <div>电影列表</div>
  `
}
const Theater = () => {
  view.innerHTML = `
    <div>影院列表</div>
  `
}

function render() {
  let pathname = location.pathname

  switch(pathname) {
    case '/':
    case '/movie':
      // history.pushState({id: 2}, '', '/movie')
      Movie()
      break;
    case '/theater':
      // history.pushState({id: 2}, '', '/theater')
      Theater()
      break;
    default:
      break;
  }
}

// popstate, 在浏览器的前进后退按钮被点击的时候触发
window.addEventListener('popstate', () => {
  render()
}, false)

document.querySelector('#back').addEventListener('click', () => {
  history.back()
}, false)

document.querySelector('#go').addEventListener('click', () => {
  history.go(1)
  console.log(history.state)
}, false)

lis.forEach((li, index) => {
  li.addEventListener('click', () => {
    const to = li.getAttribute('to')
    history.pushState({id: 2}, '', to)
    render()
  }, false)
})
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值