Vue和React路由原理

hash

复制代码
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <ul>
        <!-- 定义路由 -->
        <li><a href="#/home">home</a></li>
        <li><a href="#/about">about</a></li>

        <!-- 渲染路由对应的 UI -->
        <div id="routeView"></div>
    </ul>
    <script>
        // 页面加载完不会触发 hashchange,这里主动触发一次 hashchange 事件
        window.addEventListener('DOMContentLoaded', onHashChange)
        // 监听路由变化
        window.addEventListener('hashchange', onHashChange)

        // 路由视图
        let routerView = document.querySelector('#routeView')


        // 路由变化时,根据路由渲染对应 UI
        function onHashChange() {
            switch (location.hash) {
                case '#/home':
                    routerView.innerHTML = 'Home'
                    return
                case '#/about':
                    routerView.innerHTML = 'About'
                    return
                default:
                    return
            }
        }
    </script>
</body>

</html>
复制代码

 

history

复制代码
<html>

<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>

<body>
    <ul>
        <!-- 定义路由 -->
        <li><a href="/home">home</a></li>
        <li><a href="/about">about</a></li>
        <!-- 渲染路由对应的 UI -->
        <div id="routeView"></div>
    </ul>
</body>
<script>
    // 页面加载完不会触发 hashchange,这里主动触发一次 hashchange 事件
    window.addEventListener('DOMContentLoaded', onLoad)
    // 监听路由变化
    window.addEventListener('popstate', onPopState)

    // 路由视图
    let routerView = document.querySelector('#routeView')

    function onLoad() {

        onPopState()

        // 拦截 <a> 标签点击事件默认行为, 点击时使用 pushState 修改 URL并更新手动 UI,从而实现点击链接更新 URL 和 UI 的效果。
        let linkList = document.querySelectorAll('a[href]')
        linkList.forEach(el => el.addEventListener('click', function (e) {
            e.preventDefault()
            history.pushState(null, '', el.getAttribute('href'))
            onPopState()
        }))
    }
    // 路由变化时,根据路由渲染对应 UI
    function onPopState() {
        switch (location.pathname) {
            case '/home':
                routerView.innerHTML = 'Home'
                return
            case '/about':
                routerView.innerHTML = 'About'
                return
            default:
                return
        }
    }
</script>

</html>
复制代码

 

posted @   z_bky  阅读(14)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
· 使用C#创建一个MCP客户端
点击右上角即可分享
微信分享提示