当前位置:首页 > JavaScript

js route 实现

2026-02-01 17:57:42JavaScript

路由实现的基本方法

在JavaScript中实现路由功能通常涉及监听URL变化并根据路径渲染不同内容。常见方法包括原生API和第三方库。

监听URL变化

window.addEventListener('popstate', () => {
  const path = window.location.pathname;
  renderContent(path);
});

修改URL而不刷新页面

history.pushState({}, '', '/new-path');

基于Hash的路由实现

Hash路由利用URL中#后的部分实现无刷新跳转,兼容性较好。

初始化路由

function initRouter(routes) {
  window.addEventListener('hashchange', () => {
    const hash = window.location.hash.slice(1) || '/';
    const route = routes[hash] || routes['*'];
    route && route();
  });
}

定义路由表

const routes = {
  '/': () => renderHomePage(),
  '/about': () => renderAboutPage(),
  '*': () => renderNotFound()
};

基于History API的路由

现代SPA应用更推荐使用History API实现更干净的URL。

路由匹配逻辑

js route 实现

function matchRoute(path, routes) {
  const routeKeys = Object.keys(routes);
  const matchedKey = routeKeys.find(key => {
    if (key.includes(':')) {
      const regex = new RegExp(`^${key.replace(/:\w+/g, '([^/]+)')}$`);
      return regex.test(path);
    }
    return key === path;
  });
  return matchedKey ? routes[matchedKey] : routes['*'];
}

动态参数处理

'/user/:id': (params) => {
  console.log(`User ID: ${params.id}`);
}

第三方库集成

对于复杂应用,可考虑成熟的路由库:

React Router示例

<BrowserRouter>
  <Routes>
    <Route path="/" element={<Home />} />
    <Route path="/users/:id" element={<UserProfile />} />
  </Routes>
</BrowserRouter>

Vue Router示例

js route 实现

const routes = [
  { path: '/', component: Home },
  { path: '/about', component: About }
]
const router = VueRouter.createRouter({
  history: VueRouter.createWebHistory(),
  routes
})

路由守卫实现

保护特定路由需要验证逻辑:

认证检查

function requireAuth(to, from, next) {
  if (isLoggedIn()) next();
  else next('/login');
}

路由配置

{
  path: '/dashboard',
  component: Dashboard,
  beforeEnter: requireAuth
}

性能优化技巧

代码分割

const LazyComponent = React.lazy(() => import('./LazyComponent'));

预加载策略

router.beforeEach((to, from, next) => {
  if (to.meta.preload) {
    preloadComponent(to.component);
  }
  next();
});

标签: jsroute
分享给朋友:

相关文章

js实现

js实现

实现 JavaScript 功能的方法 在 JavaScript 中实现特定功能通常涉及多个步骤。以下是常见的实现方法: 基础语法和变量声明 使用 let 或 const 声明变量: let co…

js实现复制功能

js实现复制功能

使用 document.execCommand 方法 这种方法适用于较旧的浏览器,但在现代浏览器中可能被逐步淘汰。通过创建一个临时的 textarea 元素,将文本内容放入其中,然后执行复制命令。…

js实现pdf在线预览

js实现pdf在线预览

使用PDF.js实现PDF在线预览 PDF.js是由Mozilla开发的一个开源JavaScript库,可以在网页中直接渲染PDF文件。以下是实现PDF在线预览的步骤: 引入PDF.js库 在HT…

js实现拷贝

js实现拷贝

实现文本拷贝 使用 document.execCommand 方法(已废弃但兼容性较好): function copyText(text) { const textarea = document…

js实现祖玛

js实现祖玛

实现祖玛游戏的核心思路 祖玛游戏的核心玩法是发射彩色珠子,形成三个或以上相同颜色的珠子即可消除。以下是使用JavaScript实现的基本框架。 游戏初始化 创建画布并初始化游戏状态: const…

js实现选题

js实现选题

实现选题功能的JavaScript方法 基础实现方案 使用数组存储选项,通过随机索引选取: const options = ['选项A', '选项B', '选项C', '选项D']; const r…