美文网首页从实例学习js语法特性
hash实现前端路由实例及addEventListener事件监

hash实现前端路由实例及addEventListener事件监

作者: 鹏禾呈 | 来源:发表于2018-03-16 09:35 被阅读0次

前端路由的核心原理是更新页面但不向服务器发起请求,目前在浏览器环境中这一功能的实现主要有两种方式:

HTML代码

<section>
    <ul>
        <li><a href="#/">全部</a></li>
        <li><a href="#/html">html课程</a></li>
        <li><a href="#/css">css课程</a></li>
        <li><a href="#/javascript">javascript课程</a></li>
    </ul>
</section>

js代码

    class Router{
        constructor(){
            this.routs={};
            this.curURL = '';
        }
        //监听路由变化
        init(){
            console.log(this);
            window.addEventListener("hashchange", this.reloadPage);
        }
        //获取路由参数
        reloadPage(){
            console.log(this);
            this.curURL = location.hash.substring(1) || "/";
            this.routs[this.curURL]();
        }

       //保存路由对应的函数
        map(key,callback){
            this.routs[key] = callback;
        }
   }

   const iRouter = new Router();
   iRouter.map("/", ()=>{
       let oSidebar = document.querySelector("sidebar");
       oSidebar.innerHTML = 'html,css,javascript';
   })
   iRouter.map("/html",()=>{
       let oSidebar = document.querySelector("sidebar");
       oSidebar.innerHTML = 'html5';
   })
   iRouter.map("/css",()=>{
       let oSidebar = document.querySelector("sidebar");
       oSidebar.innerHTML = 'css';
   })
   iRouter.map("/javascript",()=>{
       let oSidebar = document.querySelector("sidebar");
       oSidebar.innerHTML = 'javascript';
   })
   iRouter.init();

window.addEventLister("hashchange",this.reloadPage.bind(this))

对于本渣这行代码有几个要学习知识点

  1. 当 一个窗口的哈希改变时就会触发 hashchange 事件。即URL由“index.html#/”变为“index.html#/css”时,执行reloadPage方法。
  2. 为什么使用bind, MDN关于this的文档里写到“函数被用作DOM事件处理函数时,它的this指向触发事件的元素”。这里不绑定this的话,执行时this就是window对象。
  3. bug解决,当不绑定this时点击导航会报错:Uncaught TypeError: Cannot read property '/css' of undefined at reloadPage ;控制台查看js 错误提示停留在this.routs[this.curURL](); this.reloadPage相当于window.reloadPage。window上临时生成了一个空的reloadPage方法。所以会报以上错误;

相关文章

网友评论

    本文标题:hash实现前端路由实例及addEventListener事件监

    本文链接:https://www.haomeiwen.com/subject/hgklqftx.html