前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >前端路由实现原理

前端路由实现原理

作者头像
lilugirl
发布2020-10-13 23:05:35
4940
发布2020-10-13 23:05:35
举报
文章被收录于专栏:前端导学前端导学
代码语言:javascript
复制
<!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>
    <a href="#/">主页</a>
    <a href="#/home">home</a>
    <a href="#/index">index</a>
    <div id="content"></div>

    <script>
  /*
  URL中hash值只是客户端的一种状态,也就是说当向服务器端发出请求时,hash部分不会被发送。hash值的改变,都会在浏览器的访问历史中增加一个记录。因此我们能通过浏览器的回退、前进按钮控制hash的切换。我们可以使用hashchange事件来监听hash的变化。
  */

    class Router{
        constructor({routes}){
            this.routes=routes;
            this.everyPath={};
            this.init();
            this.routes.forEach((item)=>{
                this.everyPath[item.path]=function(){
                    document.getElementById('content').innerHTML=item.component;
                };
            })
        }

        init(){
            window.addEventListener('load',this.updateLocation.bind(this))
            window.addEventListener('hashchange',this.updateLocation.bind(this))
        }

        updateLocation(){
            let pathRes=window.location.hash.slice(1);
            this.everyPath[pathRes]();
        }
    }

    new Router({
        routes:[
            {
                path:'/',
                component:"主页"
            },
            {
                path:'/home',
                component:"home"
            },
            {
                path:'/index',
                component:'index'
            }
        ]
    })
    </script>
</body>

</html>
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档