当前位置:首页 > VUE

不用vue实现切换路由

2026-01-20 03:24:44VUE

使用原生 JavaScript 实现路由切换

通过监听 URL 变化并动态加载内容,可以实现简单的路由切换功能。以下是一个基于 history.pushStatepopstate 事件的实现方式:

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

// 获取内容容器
const contentDiv = document.getElementById('content');

// 初始化路由
function navigateTo(path) {
  window.history.pushState({}, path, window.location.origin + path);
  renderContent(path);
}

// 渲染内容
function renderContent(path) {
  contentDiv.innerHTML = routes[path] || '<h1>404 Not Found</h1>';
}

// 监听浏览器前进/后退
window.addEventListener('popstate', () => {
  renderContent(window.location.pathname);
});

// 初始加载
renderContent(window.location.pathname);

使用 Hash 模式实现路由

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

不用vue实现切换路由

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

function handleHashChange() {
  const hash = window.location.hash || '#/';
  document.getElementById('content').innerHTML = routes[hash] || '<h1>404 Not Found</h1>';
}

// 初始加载和监听变化
window.addEventListener('load', handleHashChange);
window.addEventListener('hashchange', handleHashChange);

使用动态内容加载

如果需要从服务器加载内容,可以修改渲染函数:

不用vue实现切换路由

async function renderContent(path) {
  try {
    const response = await fetch(`/api/content${path}`);
    const html = await response.text();
    contentDiv.innerHTML = html;
  } catch (error) {
    contentDiv.innerHTML = '<h1>Error loading content</h1>';
  }
}

添加路由守卫功能

实现类似 Vue Router 的导航守卫:

const beforeHooks = [];

function beforeEach(callback) {
  beforeHooks.push(callback);
}

async function navigateTo(path) {
  let allowNavigation = true;

  for (const hook of beforeHooks) {
    const result = await hook(path);
    if (result === false) {
      allowNavigation = false;
      break;
    }
  }

  if (allowNavigation) {
    window.history.pushState({}, path, window.location.origin + path);
    renderContent(path);
  }
}

完整的路由类实现

封装一个更完整的路由解决方案:

class SimpleRouter {
  constructor() {
    this.routes = {};
    this.beforeHooks = [];
    this.contentElement = document.getElementById('content');

    window.addEventListener('popstate', () => this.render());
    window.addEventListener('load', () => this.render());
  }

  addRoute(path, content) {
    this.routes[path] = content;
  }

  beforeEach(callback) {
    this.beforeHooks.push(callback);
  }

  async navigate(path) {
    let allowNavigation = true;

    for (const hook of this.beforeHooks) {
      const result = await hook(path);
      if (result === false) allowNavigation = false;
    }

    if (allowNavigation) {
      window.history.pushState({}, path, window.location.origin + path);
      this.render();
    }
  }

  render() {
    const path = window.location.pathname;
    this.contentElement.innerHTML = this.routes[path] || '<h1>404 Not Found</h1>';
  }
}

// 使用示例
const router = new SimpleRouter();
router.addRoute('/', '<h1>Home Page</h1>');
router.addRoute('/about', '<h1>About Page</h1>');

这些方法提供了从简单到相对完整的路由实现方案,可以根据项目需求选择适合的方式或进行组合扩展。

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

相关文章

vue实现自动翻译

vue实现自动翻译

Vue 实现自动翻译的方法 在 Vue 项目中实现自动翻译功能可以通过多种方式完成,以下是几种常见的方法: 使用第三方翻译 API 注册并获取翻译 API 的密钥(如 Google Transla…

vue前端实现搜索

vue前端实现搜索

实现搜索功能的基本方法 在Vue中实现搜索功能通常涉及以下几个关键步骤,结合数据绑定、计算属性和方法调用来动态过滤和显示结果。 数据绑定与输入处理 使用v-model双向绑定搜索输入框的值,监听用…

vue如何实现到期提醒

vue如何实现到期提醒

实现 Vue 到期提醒功能 使用计算属性计算剩余时间 在 Vue 组件中定义一个计算属性,计算目标日期与当前日期的差值。通过 Date 对象获取时间戳并计算剩余天数或小时数。 computed: {…

vue怎么实现数据检测

vue怎么实现数据检测

Vue 数据检测的实现方式 Vue 通过响应式系统实现数据检测,核心机制基于 Object.defineProperty(Vue 2)或 Proxy(Vue 3)。以下是具体实现方法: 基于 Vu…

vue状态管理怎么实现

vue状态管理怎么实现

Vue 状态管理实现方法 使用 Vuex(官方推荐) Vuex 是 Vue 的官方状态管理库,适合中大型应用。 安装 Vuex: npm install vuex --save 创建 Store…

vue实现点击旋转轮盘

vue实现点击旋转轮盘

实现点击旋转轮盘效果 在Vue中实现点击旋转轮盘效果,可以通过CSS动画和Vue的数据绑定结合完成。以下是一个完整的实现方案: 准备工作 需要安装Vue.js环境,可以通过CDN引入或使用Vue…