前端路由之 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>
相關文章
相關標籤/搜索