当前位置:首页 > 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 表格实现方法 使用原生HTML表格 在Vue模板中直接使用HTML的<table>标签,结合v-for动态渲染数据: <template> <table&…

vue前端实现登录

vue前端实现登录

实现登录功能的基本流程 使用Vue实现登录功能需要结合前端框架和后端API交互。以下是一个典型的实现方案: 安装必要依赖 确保项目已安装axios用于HTTP请求: npm install a…

vue 实现blog

vue 实现blog

Vue 实现博客的基本步骤 使用 Vue 实现博客可以分为前端和后端两部分,前端使用 Vue.js 框架,后端可以选择 Node.js、Python 或其他服务端语言。以下是一个基于 Vue 的博客实…

vue实现博客

vue实现博客

Vue 实现博客的基本步骤 使用 Vue.js 实现一个博客系统可以分为前端和后端两部分。以下是基于 Vue 的前端实现方案,后端可以选择 Node.js、Django 或其他框架。 项目初始化 使…

vue实现注销

vue实现注销

实现用户注销功能 在Vue应用中实现用户注销功能通常涉及清除用户会话、重置应用状态并跳转到登录页面。以下是具体实现方法: 清除用户认证信息 使用Vuex或Pinia管理用户状态时,需在注销时重置存…

vue动画实现

vue动画实现

Vue动画实现方法 Vue提供了多种方式实现动画效果,主要通过内置组件和第三方库完成。 使用<transition>组件 Vue内置的<transition>组件可以为元素添…