当前位置:首页 > VUE

不用vue实现切换路由

2026-02-20 19:26:22VUE

使用原生 JavaScript 实现路由切换

通过监听 URL 变化并动态加载内容,可以无需 Vue 或其他框架实现路由切换。核心是利用 window.history API 和 popstate事件。

// 定义路由配置
const routes = {
  '/': 'Home Page Content',
  '/about': 'About Page Content',
  '/contact': 'Contact Page Content'
};

// 渲染当前路由内容
function renderRoute() {
  const path = window.location.pathname;
  document.getElementById('app').innerHTML = routes[path] || '404 Not Found';
}

// 监听浏览器前进/后退
window.addEventListener('popstate', renderRoute);

// 初始化路由
document.addEventListener('DOMContentLoaded', () => {
  document.body.addEventListener('click', e => {
    if (e.target.matches('[data-link]')) {
      e.preventDefault();
      const href = e.target.getAttribute('href');
      window.history.pushState(null, null, href);
      renderRoute();
    }
  });
  renderRoute();
});

基于 Hash 的路由实现

对于不支持 History API 的旧浏览器,可以使用 hash 路由模式:

不用vue实现切换路由

const routes = {
  '#/': 'Home Page',
  '#/about': 'About Page',
  '#/contact': 'Contact Page'
};

function handleHashChange() {
  const hash = window.location.hash || '#/';
  document.getElementById('app').innerHTML = routes[hash] || '404';
}

window.addEventListener('hashchange', handleHashChange);
window.addEventListener('load', handleHashChange);

动态内容加载方案

如果需要从服务器加载内容而非静态文本:

不用vue实现切换路由

async function loadRouteContent(path) {
  try {
    const response = await fetch(`/api/content${path}`);
    return await response.text();
  } catch (error) {
    return 'Error loading content';
  }
}

async function renderDynamicRoute() {
  const path = window.location.pathname;
  const content = await loadRouteContent(path);
  document.getElementById('app').innerHTML = content;
}

路由参数处理

实现带参数的路由匹配:

const routes = [
  { pattern: /^\/user\/(\w+)$/, handler: id => `User Profile: ${id}` },
  { pattern: /^\/post\/(\d+)$/, handler: id => `Post ID: ${id}` }
];

function matchRoute() {
  const path = window.location.pathname;
  for (const route of routes) {
    const match = path.match(route.pattern);
    if (match) {
      return route.handler(...match.slice(1));
    }
  }
  return '404 Not Found';
}

路由守卫实现

添加路由切换前的权限检查:

const auth = {
  isAuthenticated: false
};

function navigateTo(path) {
  if (path === '/admin' && !auth.isAuthenticated) {
    window.location.pathname = '/login';
    return;
  }
  window.history.pushState(null, null, path);
  renderRoute();
}

这些方案提供了从简单到进阶的路由实现方式,可根据项目需求选择或组合使用。核心思路都是通过监听 URL 变化并更新 DOM,无需依赖任何前端框架。

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

相关文章

vue广告实现

vue广告实现

Vue 广告实现方法 在 Vue 项目中实现广告功能可以通过多种方式完成,具体取决于广告类型和需求。以下是几种常见的实现方法: 使用第三方广告平台 许多广告平台如 Google AdSense、百…

vue 实现挂载

vue 实现挂载

Vue 实现挂载的基本方法 在 Vue 中,挂载是将 Vue 实例与 DOM 元素关联的过程。通过挂载,Vue 可以管理 DOM 并实现数据绑定和响应式更新。 创建 Vue 实例并挂载 const…

vue实现active

vue实现active

Vue 实现 active 状态的方法 在 Vue 中实现 active 状态可以通过以下几种方式实现,具体取决于使用场景和需求。 使用 v-bind:class 动态绑定类名 通过 v-bind:…

vue mvvm 实现

vue mvvm 实现

Vue MVVM 实现原理 Vue.js 的 MVVM(Model-View-ViewModel)架构通过数据绑定和响应式系统实现视图与数据的自动同步。以下是其核心实现机制: 数据劫持与响应式系统…

vue指令实现

vue指令实现

Vue 指令的实现方式 Vue 指令是特殊的标记,用于在 DOM 元素上应用特定的行为。可以通过全局或局部方式注册自定义指令。 全局注册指令 在 Vue 应用中通过 Vue.directive 方法…

vue实现绘图

vue实现绘图

Vue 实现绘图的方法 在 Vue 中实现绘图功能,可以通过多种方式实现,包括使用原生 HTML5 Canvas、第三方库(如 Fabric.js、Konva.js)或 SVG。以下是几种常见的实现方…