当前位置:首页 > VUE

js原生实现vue路由

2026-01-22 11:05:33VUE

使用 History API 实现路由切换

通过 window.history.pushStatepopstate 事件可以实现前端路由的无刷新跳转。创建一个路由对象管理路径与组件的映射关系。

class SimpleRouter {
  constructor(routes) {
    this.routes = routes;
    this.currentComponent = null;
    window.addEventListener('popstate', () => this.handleRouteChange());
  }

  handleRouteChange() {
    const path = window.location.pathname;
    const route = this.routes.find(r => r.path === path);
    if (route) {
      this.currentComponent = route.component;
      this.render();
    }
  }

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

  render() {
    const app = document.getElementById('app');
    app.innerHTML = '';
    app.appendChild(this.currentComponent());
  }
}

配置路由与组件映射

定义路由配置数组,每个路由对象包含路径和对应的组件渲染函数。

const routes = [
  {
    path: '/',
    component: () => {
      const div = document.createElement('div');
      div.textContent = 'Home Page';
      return div;
    }
  },
  {
    path: '/about',
    component: () => {
      const div = document.createElement('div');
      div.textContent = 'About Page';
      return div;
    }
  }
];

const router = new SimpleRouter(routes);
router.handleRouteChange(); // 初始化路由

实现导航链接

创建自定义的 <a> 标签,阻止默认跳转行为并使用路由的 navigate 方法。

document.querySelectorAll('a[data-router]').forEach(link => {
  link.addEventListener('click', (e) => {
    e.preventDefault();
    router.navigate(e.target.getAttribute('href'));
  });
});

处理动态路由参数

通过正则表达式匹配动态路径,并提取参数传递给组件。

// 修改路由配置
{
  path: '/user/:id',
  component: (params) => {
    const div = document.createElement('div');
    div.textContent = `User ID: ${params.id}`;
    return div;
  }
}

// 修改路由类的handleRouteChange方法
handleRouteChange() {
  const path = window.location.pathname;
  const route = this.routes.find(r => {
    const regex = new RegExp(`^${r.path.replace(/:\w+/g, '(\\w+)')}$`);
    return regex.test(path);
  });

  if (route) {
    const params = this.extractParams(route.path, path);
    this.currentComponent = () => route.component(params);
    this.render();
  }
}

extractParams(routePath, actualPath) {
  const params = {};
  const routeParts = routePath.split('/');
  const actualParts = actualPath.split('/');

  routeParts.forEach((part, i) => {
    if (part.startsWith(':')) {
      params[part.slice(1)] = actualParts[i];
    }
  });

  return params;
}

添加路由守卫功能

通过中间件机制实现路由跳转前的权限校验。

class SimpleRouter {
  constructor(routes, guards = []) {
    this.guards = guards;
    // ...其他初始化代码
  }

  async navigate(path) {
    let allowNavigation = true;
    for (const guard of this.guards) {
      if (!await guard(path)) {
        allowNavigation = false;
        break;
      }
    }

    if (allowNavigation) {
      window.history.pushState({}, '', path);
      this.handleRouteChange();
    }
  }
}

// 使用示例
const authGuard = async (path) => {
  if (path === '/admin' && !isLoggedIn()) {
    return false;
  }
  return true;
};

const router = new SimpleRouter(routes, [authGuard]);

js原生实现vue路由

标签: 路由js
分享给朋友:

相关文章

vue实现前端路由

vue实现前端路由

Vue 实现前端路由的方法 Vue 可以通过 Vue Router 实现前端路由管理。以下是具体实现步骤: 安装 Vue Router 通过 npm 或 yarn 安装 Vue Router:…

vue实现路由跳转

vue实现路由跳转

Vue 路由跳转的实现方式 在 Vue 中,路由跳转可以通过 vue-router 实现,以下是几种常见的方法: 声明式导航(模板中使用 <router-link>) 通过 <ro…

vue路由实现原理

vue路由实现原理

Vue 路由实现原理 Vue Router 是 Vue.js 的官方路由管理器,其核心原理基于前端路由的实现方式,主要包括哈希模式(Hash Mode)和历史模式(History Mode)。 哈…

vue 路由 实现

vue 路由 实现

Vue 路由实现方法 Vue 路由通常通过 Vue Router 实现,它是 Vue.js 官方的路由管理器,用于构建单页应用(SPA)。以下是具体实现步骤: 安装 Vue Router 通过 np…

js实现拖拽

js实现拖拽

实现拖拽的基本步骤 通过监听鼠标事件(mousedown、mousemove、mouseup)实现拖拽功能。以下是核心代码逻辑: const draggableElement = document.…

js实现全屏

js实现全屏

实现全屏的基本方法 使用JavaScript实现全屏功能主要依赖Element.requestFullscreen()方法。现代浏览器均支持此API,但不同浏览器可能需要添加前缀。 // 触发全屏…