手写实现简易版前端history路由和hash路由

本文通过两个示例介绍了前端路由的两种常见实现方式:history路由和hash路由。在history模式中,利用浏览器的history.pushState方法改变URL而不进行页面刷新,通过监听popstate事件更新页面内容。而在hash模式下,路由变化体现在URL的hash部分,通过监听hashchange事件来更新页面。这两种方式都是为了实现单页应用中页面状态的切换。
摘要由CSDN通过智能技术生成

history路由

<!DOCTYPE html>
<html lang="zh-CN">
<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>history路由</title>
</head>
<body>
  <div class="router">
    <a href="./">首页</a>
    <a href="./user">用户列表</a>
    <a href="./about">关于我们</a>
  </div>
  <div class="content"></div>

  <script>
    class BaseRouter {
      constructor () {
        // 路由表
        this.routes = {}
      }

      // 收集路由
      route (path, cb) {
        this.routes[path] = cb || function () {}
      }

      // 访问路由
      go (path) {
        window.history.pushState({path}, null, path)
        const cb = this.routes[path]
        if (cb) cb()
      }
    }
	
	//实例化路由对象
    const Route = new BaseRouter()
    //添加路由
    Route.route('./', () => {changeText('这是首页页面')})
    Route.route('./user', () => {changeText('这是用户页面')})
    Route.route('./about', () => {changeText('这是关于我们页面')})
	
    function changeText (text) {
      let dom = document.querySelector('.content')
      dom.innerHTML = text
    }

    document.querySelector('.router').addEventListener('click', e => {
      if (e.target.tagName === 'A') {
        e.preventDefault()
        Route.go(e.target.getAttribute('href'))
      }
    })
  </script>
</body>
</html>

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>hash 路由</title>
</head>
<body>
    <div id="container">
        <a href="#">首页</a> 
        <a href="#about">关于我们</a>
        <a href="#user">用户列表</a>
    </div>
    <div id="context"></div>
    <script>
        class BaseRouter {
            constructor() {
                this.routes = {};
                this.refresh = this.refresh.bind(this);

                window.addEventListener('load', this.refresh);
                window.addEventListener('hashchange', this.refresh);
            };

            // 对路由进行收集
            route(path, cb) {
                this.routes[path] = cb || function(){};
            };

            

            refresh() {
                const path = `/${window.location.hash.slice(1) || ''}`;
                this.routes[path]();
            }
        }

        const Route = new BaseRouter();

        Route.route('/about', () => changeText("关于我们页面"));
        Route.route('/user', () => changeText("用户列表页"));
        Route.route("/", () => changeText("首页页面"));

        function changeText(arg) {
            document.getElementById('context').innerHTML = arg;
        }
    </script>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值