前端路由之 History路由原生实现

History路由的实现

history 实现路由主要依靠两个API,前进或后退可以配合onpopstate事件

  • history.pushState

    • 将当前URL和history.state加入到history中,并用新的state和URL替换当前,不会造成页面刷新
    • state:与要跳转到的URL对应的状态信息
    • title:title
    • url:要跳转到的URL地址,不能跨域
    • pushState会向浏览器的历史堆栈添加一个url为设定值的记录,并指向当前项
  • history.replaceState

    • 与pushState参数,含义相同
    • 区别在于replaceState是替换浏览器历史堆栈的当前历史记录为设定的url
    • replaceState不会改动浏览器历史堆栈的当前指向

代码(详细注释)

<ul>
    <li><a href="?name=red">A</a></li>
    <li><a href="?name=blue">B</a></li>
    <li><a href="?name=green">C</a></li>
</ul>
<div style='width: 100px; height: 100px;'></div>
<script>
    function setBackgroundColor(color) {
        document.querySelector('div').style.backgroundColor = color;
    }

    /**
     * [color description]
     * @type {String}
     * 1. data 参数
     * 2. title
     * 3. url
     */
    // 将页面替换成当前url的页面
    history.replaceState({
        color: 'red'
    }, '当前为A页面', "?name=a");
    setBackgroundColor("red");

    // 浏览器前进后退就会触发popstate事件, 通过事件的 state 可以获得参数值
    window.onpopstate = function (event) {
        // console.log(event.state);
        setBackgroundColor(event.state.color);
    }

    let aObj = document.querySelectorAll('a');
    aObj.forEach((item) => {
        item.addEventListener('click', function(event) {
            event.preventDefault();
            // 请求地址
            let query = this.href.split('?')[1];
            // 请求的参数值
            let color = query.split('=')[1];
            // history.state:获取历史栈中最顶端的state数据(即history.pushState中的第一个参数)
            if(history.state.color !== color) {
                setBackgroundColor(color);
                // 放入历史记录中
                history.pushState({color: color},color, location.href.split('?')[0] + '?' + query);
            }
        })
    })
</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值