js写一个route路由

路由的用途:做H5的时候,可以把所有页面写在一张页面里面,通过路由,来显示你点击过后需要出现的页面。

路由实现的原理:window绑定了监听函数,当url的hash值发生变化的时候会触发hashchange回调,在回调中进行不同的操作,马上刷新页面,从而显示不同的页面。

js代码如下

// 创建一个 newRouter 类
    class newRouter {
    // 初始化路由信息
    
    constructor() {        //构造方法
    this.routes = {};
    this.currentUrl = '';
    }

    // 切割 hash,渲染页面
    refresh() {
    this.currentUrl = location.hash.slice(1) || '/';          		 //location.hash获得#/setting  /this.currentUrl获得/setting
    this.routes[this.currentUrl] && this.routes[this.currentUrl]();    //回调函数
    }

    // 初始化
    init() { //加载或者路径发生变化时 刷新构造函数 中的变量
    window.addEventListener('load', this.refresh.bind(this), false);        //加一个监听函数,绑定this    this指向这个类
    window.addEventListener('hashchange', this.refresh.bind(this), false);
    }

    // 传入 URL 以及 根据 URL 对应的回调函数

    route(path, callback = () => {}) {
    this.routes[path] = callback;
    }
    }

    // new 一个 Router 实例
    window.Router = new newRouter();

    // 路由实例初始化
    window.Router.init();

    Router.route('/setting', () => {
        document.querySelector(".wrap").style.display="none";
        document.querySelector(".settingWrap").style.display="block";
    });
    Router.route('/back', () => {
        document.querySelector(".wrap").style.display="block";
        document.querySelector(".settingWrap").style.display="none";
    });
    </script>

html

<a href="#/setting">点击这个就切换路径了</a>   // 样式是wrap
<a href="#/back">点击这个就又切换路径了</a>   //样式是settingWrap

但是这个路由写在下面,不然style改变不了

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值