html 单页面路由模式hash和history

Hash 模式

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <nav class="nav-box">
    <a href="#/">首页</a>
    <a href="#/about">关于</a>
    <a href="#/product">产品</a>
  </nav>

  <div id="app"></div>

  <script>
    const app = document.querySelector('#app')
    const navBox = document.querySelector('.nav-box')

    const routes = [
      {
        path: '/',
        component: '组件-首页home' // 应是组件
      },
      {
        path: '/about',
        component: '组件-关于我们'
      },
      {
        path: '/product',
        component: '组件-产品列表'
      }
    ]
    
    const routeMatch = () => {
      const hash = location.hash.substring(1) // 去掉hash的 #
      let text = ''
      routes.forEach(it => {
        if(it.path === hash) text = it.component
      })
      app.innerHTML = text
    }

    // 首次渲染 /
    location.hash = '/'
    routeMatch()
    // 监听 hash 变化
    window.onhashchange = routeMatch
  </script>
</body>
</html>

H5的history模式

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <nav class="nav-box">
    <a href="/">首页</a>
    <a href="/about">关于</a>
    <a href="/product">产品</a>
  </nav>

  <div id="app"></div>

  <script>
    const app = document.querySelector('#app')
    const navBox = document.querySelector('.nav-box')

    const routes = [
      {
        path: '/',
        component: '组件-首页home' // 应是组件
      },
      {
        path: '/about',
        component: '组件-关于我们'
      },
      {
        path: '/product',
        component: '组件-产品列表'
      }
    ]
    
    // 事件委托,点击事件
    navBox.onclick = (event) => {
      if(event.target.tagName === 'A') {
        event.preventDefault() // 阻止默认事件,跳转并刷新
        // Failed to execute 'pushState' on 'History': A history state object with URL ' cannot be created in a document with origin 'null' and URL '
        history.pushState({}, '', event.target.href)
        routeMatch()
      }
    }

    const routeMatch = () => {
      const pathname = location.pathname
      let text = ''
      routes.forEach(it => {
        if(it.path === pathname) text = it.component
      })
      app.innerHTML = text
    }

    // 首次渲染 /
    history.pushState(null, '', '/')
    routeMatch()

    // 监听popstate地址变化事件; 执行go/forward/back等方法可以触发
    window.onpopstate = routeMatch

  </script>
</body>
</html>
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值