基于hash的改变实现SPA

一、原理主要是通过window.onhashchange方法监听window.location.hash的改动

  1. 这里我直接用a元素来改变hash
  2. 通过设置dom节点的innerHTML,来实现页面切换
  3. hashRouter对象中使用'#404'进行兜底,保留一个带有href=""的a元素来回到首页
<!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 Router Demo</title>
    <style>
        #root {
            text-align: center;
        }
        .comment {
            color: red;
        }
    </style>
</head>

<body>
    <div id="root">
        <div class="navbar">
            <a class="hashlink" href="">首页</a>
            <a class="hashlink" href="#article">文章</a>
            <a class="hashlink" href="#image">图片</a>
            <a class="hashlink" href="#comment">评论</a>
        </div>
        <div class="routerView">
            我是首页
        </div>
    </div>
    <script type="module">
        const hashRouter = {
            '': `我是首页`,
            '#404': "<div>404 Not Found</div>",
            '#article': `<p>这是一个段落。</p>
                        <p>这是一个段落。</p>
                        <p>这是一个段落。</p>`,
            '#image': `<img src="https://www.runoob.com/images/logo.png" width="258" height="39" />`,
            '#comment': `<div class="comment">这是一条评论</div>`,
        };

        (function () {
            function onHashChange(){
                const currentHash = window.location.hash;
                const routerView = document.querySelector('.routerView');
                const template = hashRouter[currentHash] ?? hashRouter['#404'];
                routerView.innerHTML = template;
            }
            onHashChange();
            window.onhashchange = onHashChange;
        })();
    </script>
</body>

</html>

二、效果

  1. 开始
    image

  2. 点击文章
    image

  3. 点击图片
    image

  4. 点击评论
    image

  5. 点击首页
    image

posted @ 2023-03-14 18:18  pangqianjin  阅读(21)  评论(0编辑  收藏  举报