zoukankan      html  css  js  c++  java
  • 原生JS实现一个简单的前端路由(原理)

    说一下前端路由实现的简要原理,以 hash 形式(也可以使用 History API 来处理)为例,

    当 url 的 hash 发生变化时,触发 hashchange 注册的回调,回调中去进行不同的操作,进行不同的内容的展示。

    直接看代码或许更直观。

     1 function Router() {
     2     this.routes = {};
     3     this.currentUrl = '';
     4 }
     5 Router.prototype.route = function(path, callback) {
     6     this.routes[path] = callback || function(){};
     7 };
     8 Router.prototype.refresh = function() {
     9     this.currentUrl = location.hash.slice(1) || '/';
    10     this.routes[this.currentUrl]();
    11 };
    12 Router.prototype.init = function() {
    13     window.addEventListener('load', this.refresh.bind(this), false);
    14     window.addEventListener('hashchange', this.refresh.bind(this), false);
    15 }
    16 window.Router = new Router();
    17 window.Router.init();

    上面路由系统 Router 对象实现,主要提供三个方法

    • init 监听浏览器 url hash 更新事件
    • route 存储路由更新时的回调到回调数组routes中,回调函数将负责对页面的更新
    • refresh 执行当前url对应的回调函数,更新页面

    Router 调用方式以及呈现效果如下:点击触发 url 的 hash 改变,并对应地更新内容(这里为 body 背景色)

    <ul> 
        <li><a href="#/">turn white</a></li> 
        <li><a href="#/blue">turn blue</a></li> 
        <li><a href="#/green">turn green</a></li> 
    </ul> 
    var content = document.querySelector('body');
    // change Page anything
    function changeBgColor(color) {
        content.style.backgroundColor = color;
    }
    Router.route('/', function() {
        changeBgColor('white');
    });
    Router.route('/blue', function() {
        changeBgColor('blue');
    });
    Router.route('/green', function() {
        changeBgColor('green');
    });

  • 相关阅读:
    android UI 适配小节
    Android中的倒计时实现
    几种适配器&观察者&ListView之间的那点事
    Service stopSelf(int statId)和onStartcommand(Intent intent,int flags,int startId)
    java 虚函数
    java 重载和多态的区别
    小程序体验版路径以及参数携带
    微信小程序--上传图片公用组件
    微信小程序页面返回
    js兼容安卓和IOS的复制文本到剪切板
  • 原文地址:https://www.cnblogs.com/exhuasted/p/6839515.html
Copyright © 2011-2022 走看看