当前位置:首页 > JavaScript

js route 实现

2026-04-06 10:55:05JavaScript

路由实现的基本概念

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

Hash模式路由实现

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

js route 实现

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。

js route 实现

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}`));

路由守卫实现

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

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
分享给朋友:

相关文章

jquery.js

jquery.js

jQuery 是一个快速、简洁的 JavaScript 库,简化了 HTML 文档遍历、事件处理、动画设计和 Ajax 交互等操作。以下是关于 jQuery.js 的核心信息和使用方法: 获…

js实现tab选项卡切换

js实现tab选项卡切换

实现Tab选项卡切换的JavaScript方法 使用纯JavaScript实现Tab切换功能,可以通过监听点击事件动态切换内容显示状态。以下是两种常见实现方式: 基础DOM操作实现 /…

js实现抽奖

js实现抽奖

实现抽奖功能的基本思路 抽奖功能的核心是随机选择奖项并展示结果。可以通过数组存储奖项,利用随机数生成索引,最后通过动画增强用户体验。 准备奖项数据 定义一个数组存储奖项信息,每个奖项可以包含名称、图…

js实现游标

js实现游标

使用JavaScript实现游标 在JavaScript中,可以通过操作DOM元素的cursor样式属性来实现自定义游标效果。以下是几种常见的实现方法: 修改默认鼠标指针样式 通过CSS的curso…

使用js实现

使用js实现

使用JavaScript实现 JavaScript可以通过Math.random()函数生成随机数,结合其他方法可以实现多种随机数生成需求。 // 生成0到1之间的随机小数 const random…

js实现div隐藏

js实现div隐藏

使用CSS的display属性隐藏div 通过设置元素的display属性为none,可以完全隐藏div元素。这种方法不仅隐藏元素,还会从文档流中移除,不占据页面空间。 document.getEl…