现代主流框架路由原理 hash、history的底层原理

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>   
    <!-- hash -->
    <!-- <a href="#/hash">hash</a>
    <a href="#/history">历史</a> -->
    <a id="hash" href="/hash">hash</a>
    <a id="history" href="/history">历史</a>
    <div id="html">

    </div>
<script>     
    //hash
    // window.addEventListener('load',()=>{
    //     html.innerHTML = location.hash.slice(1);
    // });
    // window.addEventListener('hashchange',()=>{
    //     html.innerHTML = location.hash.slice(1)
    // });

    //history 
    function go(path) {
         history.pushState({}, null, href);
        html.innerHTML = href;
    }
    hash.onclick = function () {
        let href = this.getAttribute('href');
        go(href);
        return false;
    }
    history.onclick = function () {
            let href = this.getAttribute('href');
            go(href);
            return false;
    }
    window.addEventListener('popstate',()=>{
        go(location.pathname);
    })

</script>
</body>
</html>
原文地址:https://www.cnblogs.com/y-y-y-y/p/11102062.html