zoukankan      html  css  js  c++  java
  • 前端路由实现原理

    BOM对象;tips:为啥在这罗列下BOM,因为下面实现的两种路由模式中用到location、history中的属性和方法
    window对象,JS顶层对象,其他的BOM对象都是window对象的属性;
    document对象,文档对象;
    location对象,浏览器当前URL信息;
    navigator对象,浏览器本身信息;
    screen对象,客户端屏幕信息;
    history对象,浏览器访问历史信息;

    前端路由实现原理

    基础路由

    class BaseRouter {
      constructor(list){
        this.list = list
      }
      render(state){
        //要么找到路由对应的组件,要么配置的 * 代表404页面组件
        let ele = this.list.find( item => item.path === state );
        ele = ele ? ele : this.find( item => item.path === '*')
        //ELEMENT:就当成 let zjy = document.getElementById('zjy')这种DOM
        ELEMENT.innerText = ele.component
      }
    }

    hash模式

    class HashRouter extends BaseRouter {
      constructor(list){
        super(list)
        //history模式同理
        //初次加载配置跟路由的页面组件
        this.handler()
        //添加监听,加载组件页面
        window.addEventListener('hashchange',()=>{
          this.handler()
        },false)
      }
      handler(){
        this.render(this.getState())
      }
      getState(){
        const hash = location.hash
        return hash ? hash.splice('1') : '/'
      }
      push(path){
        location.hash = path
      }
      getUrl(path){
        const href = location.href
        const index = href.indexOf('#')
        const base = index >= 0 ? href.splice(index) : href
        return `${base}#${path}`
      }
      replace(path){
        location.replace(this.getUrl(path))
      }
      go(n){
        history.go(n)
      }
    }

    history模式

    class HistoryRouter extends BaseRouter {
      constructor(list){
        super(list)
        this.handler()
        window.addEventListener('popstate',()=>{
          this.handler()
        },false)
      }
      handler(){
        this.render(this.getState())
      }
      getState(){
        const path = location.pathname
        return path ? path : '/'
      }
      push(path){
        history.pushState(null,null,path)
        this.handler()
      }
      replace(path){
        history.replaceState(null,null,path)
        this.handler()
      }
      go(n){
        history.go(n)
      }
    }
    

      

  • 相关阅读:
    智能电视可以安装软件就可以摆脱很多限制,而且可以和PC共享影音资源这个很靠谱。
    【转载】福昕PDF电子文档处理套件 企业版 注册码 注册方法
    OS X系列文章 AirPlay+Apple TV影音方案研究[转]
    SHARP 316L打印机64位驱动问题
    我和电脑的二三事
    北信源DeviceRegister.exe的卸载方法 【转】
    上篇随笔的补充。
    ApplicationCommands用于表示应用程序程序员经常遇到的常见命令,类似于ctrl+c
    WPF中类似使用tab键功能,可以向上向下定位
    c#通过datatable导出excel和word
  • 原文地址:https://www.cnblogs.com/zhenjianyu/p/12965857.html
Copyright © 2011-2022 走看看