[TOC]

两种方式:hash,history

hash介绍

  • url有个#符号,但是#只是客户端得状态,实不会传来服务器
  • hash得更改,不会导致页面更新
  • hash得更改,会在浏览器的访问历史中添加一条记录,所以我们可以通过浏览器得返回前端按钮控之hash得切换
  • hash得更改,会触发 hashchange 事件,实例:

    location.hash = '#aaa';
    location.hash = '#bbb';
    window.addEventListenter('hashchange', () => {});
    
  • html标签得方式

    <a href="#user">点击跳转</a> 
    等同于
    location.hash = '#user';
    

hash路由原理代码

<div class="box">
    <a href='#red'>红色</a>
    <a href='#orange'>橙色</a>
    <a href='#yellow'>黄色</a>
    <a href='#green'>绿色</a>
</div>
<script>
    class Router {
        constructor() {
            this.routes = {}; // 初始化路由对象
            window.addEventListener('hashchange', () => {
                this.refresh();
            })
        }

        route(path, callback) {
            this.routes[path] = callback || function () {} // key => 路由  value => 路由对应的事件
        }

        refresh() {
            const hashUrl = `/${location.hash.slice(1)}`; // #red =>  /red
            this.routes[hashUrl]();
        }
    }

 const router = new Router();
 router.route('/red', function() {
     document.querySelector('body').style.background = 'red';
 })
 router.route('/orange', function() {
     document.querySelector('body').style.background = 'orange';
 })
 router.route('/yellow', function() {
     document.querySelector('body').style.background = 'yellow';
 })
 router.route('/green', function() {
     document.querySelector('body').style.background = 'green';
 })
</script>

history

  • html history用法

    window.history.back(); // 后退
    window.history.forward(); // 前进
    window.history.go(-1); // 接收number,后退1页
    window.history.pushState();
    window.history.replaceState();
    
  • pushState和replaceState的参数

    • state:是一个对象,是一个与指定网址相关的对象,当popstate事件触发的时候,该对象会传入回调函数
    • title:新页面的标题,浏览器支持不一,null
    • url:页面的新地址
  • history特点

    • 没有#
    • pushState/replaceState 并不会触发 popstate 事件,这是我们需要手动触发页面的重新渲染
    • 可以用popstate来监听url的变化
    • popstate到底什么才能触发
      • 点击浏览器前进/后退按钮
      • 调用back/forward/go方法
    • 面试题:vue-router怎么记住前一个页面的滚动条的位置image.png

      • 手动点击浏览器的返回或前进,基于history的go,back,forward,back
      • router-link是不能记住的

        history路由原理代码

        ```html

        返回

        ```