当前位置:首页 > JavaScript

js route 实现

2026-04-06 10:55:05JavaScript

路由实现的基本概念

在JavaScript中实现路由通常涉及监听URL变化并根据不同路径显示不同内容。前端路由有两种主要模式:Hash模式和History模式。

Hash模式路由实现

Hash模式利用URL中的#符号实现路由变化,不会触发页面刷新。

class HashRouter {
  constructor() {
    this.routes = {};
    window.addEventListener('hashchange', this.load.bind(this));
  }

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

  load() {
    const hash = window.location.hash.slice(1) || '/';
    const callback = this.routes[hash];
    if (callback) callback();
  }
}

// 使用示例
const router = new HashRouter();
router.addRoute('/', () => console.log('Home Page'));
router.addRoute('/about', () => console.log('About Page'));

History模式路由实现

History模式使用HTML5 History API实现更干净的URL。

class HistoryRouter {
  constructor() {
    this.routes = {};
    window.addEventListener('popstate', this.load.bind(this));
  }

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

  navigate(path) {
    history.pushState({}, '', path);
    this.load();
  }

  load() {
    const path = window.location.pathname;
    const callback = this.routes[path];
    if (callback) callback();
  }
}

// 使用示例
const router = new HistoryRouter();
router.addRoute('/', () => console.log('Home Page'));
router.addRoute('/about', () => console.log('About Page'));

动态路由处理

处理带参数的动态路由需要解析URL中的变量。

class DynamicRouter extends HistoryRouter {
  load() {
    const path = window.location.pathname;

    // 匹配动态路由
    for (const route in this.routes) {
      const routeRegex = new RegExp('^' + route.replace(/:\w+/g, '([^/]+)') + '$');
      const match = path.match(routeRegex);

      if (match) {
        const params = this.extractParams(route, match);
        this.routes[route](params);
        return;
      }
    }

    console.error('Route not found');
  }

  extractParams(route, match) {
    const paramNames = [...route.matchAll(/:(\w+)/g)].map(m => m[1]);
    return paramNames.reduce((params, name, i) => {
      params[name] = match[i+1];
      return params;
    }, {});
  }
}

// 使用示例
const router = new DynamicRouter();
router.addRoute('/user/:id', (params) => console.log(`User ID: ${params.id}`));

路由守卫实现

添加路由守卫可以在导航前进行权限检查。

js route 实现

class GuardedRouter extends HistoryRouter {
  constructor() {
    super();
    this.beforeHooks = [];
  }

  beforeEach(guard) {
    this.beforeHooks.push(guard);
  }

  navigate(path) {
    this.runGuards(path, () => {
      super.navigate(path);
    });
  }

  runGuards(path, next) {
    let index = 0;
    const runNextGuard = () => {
      if (index < this.beforeHooks.length) {
        this.beforeHooks[index++](path, runNextGuard);
      } else {
        next();
      }
    };
    runNextGuard();
  }
}

// 使用示例
const router = new GuardedRouter();
router.beforeEach((path, next) => {
  console.log(`Checking access to ${path}`);
  next();
});

这些实现展示了JavaScript中路由的核心概念,可以根据项目需求进行扩展或简化。实际项目中通常会使用现有的路由库如React Router或Vue Router,它们提供了更完善的功能和更好的开发体验。

标签: jsroute
分享给朋友:

相关文章

js实现

js实现

JavaScript 实现方法 JavaScript 是一种广泛使用的编程语言,适用于网页开发、服务器端编程以及移动应用开发。以下是几种常见的 JavaScript 实现方法: 网页交互功能 使用…

js实现vr

js实现vr

使用WebXR API实现VR体验 WebXR是浏览器中实现VR和AR体验的标准API,它取代了早期的WebVR。现代浏览器如Chrome、Edge和Firefox已支持WebXR。 // 初始化W…

js类实现

js类实现

使用类实现 JavaScript 功能 在 JavaScript 中,类(Class)是一种语法糖,基于原型继承机制。通过 class 关键字可以更直观地定义对象模板。 基本类定义 class…

js实现投球

js实现投球

实现投球动画的基本思路 使用JavaScript和CSS动画结合的方式模拟投球效果。核心是通过改变元素的位置、旋转和缩放属性,配合定时器或CSS过渡实现平滑动画。 创建基础HTML结构 <di…

节流js实现

节流js实现

节流(Throttle)的实现原理 节流是一种限制函数执行频率的技术,确保函数在一定时间间隔内最多执行一次。适用于高频触发事件(如滚动、输入、窗口调整等)的场景。 基础实现方式 使用时间戳判断是否执…

js实现文字滚动

js实现文字滚动

实现文字滚动的几种方法 使用CSS动画实现滚动 通过CSS的@keyframes和transform属性可以实现平滑的文字滚动效果。 <style> .scroll-text { w…