当前位置:首页 > 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());
  }
}

配置路由与组件映射

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

js原生实现vue路由

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 方法。

js原生实现vue路由

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路由实现

vue路由实现

Vue 路由实现 Vue Router 是 Vue.js 的官方路由管理器,用于构建单页面应用(SPA)。以下是 Vue Router 的基本实现步骤和核心功能。 安装 Vue Router 通过…

vue实现路由

vue实现路由

Vue 路由的实现方法 Vue 路由可以通过 Vue Router 库来实现,Vue Router 是 Vue.js 官方的路由管理器,用于构建单页面应用(SPA)。 安装 Vue Router…

js 实现vue

js 实现vue

实现 Vue 的核心功能 在 JavaScript 中实现 Vue 的核心功能需要模拟数据绑定、虚拟 DOM 和响应式系统。以下是一个简化版的实现思路: 响应式系统 通过 Object.define…

vue实现户籍系统路由实现

vue实现户籍系统路由实现

户籍系统路由实现(Vue.js) 户籍系统通常需要管理居民信息、户籍变动、统计查询等功能模块。以下基于Vue Router的实现方案: 路由模块设计 在src/router/index.js中定义…

vue路由实现iframe

vue路由实现iframe

在Vue中实现iframe嵌入可以通过路由配置和组件动态加载来完成。以下是具体实现方法: 路由配置 在Vue Router的路由配置中,通过component属性动态加载iframe组件。需要将目标…

js实现拖拽

js实现拖拽

实现拖拽的基本步骤 使用JavaScript实现拖拽功能需要监听鼠标事件,包括mousedown、mousemove和mouseup。以下是实现的基本逻辑: const draggableEleme…