当前位置:首页 > 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实现div

vue实现div

Vue 实现 DIV 元素的方法 在 Vue 中实现 DIV 元素可以通过多种方式,以下是几种常见的实现方法: 使用模板语法 在 Vue 的模板中直接使用 HTML 的 <div> 标签…

vue实现拖放

vue实现拖放

Vue 实现拖放功能 Vue 中实现拖放功能通常可以通过 HTML5 的原生拖放 API 或第三方库(如 vuedraggable)来实现。以下是两种方法的详细说明。 使用 HTML5 原生拖放 A…

vue 实现拖拽

vue 实现拖拽

Vue 实现拖拽功能 使用 HTML5 原生拖拽 API HTML5 提供了原生的拖拽 API,可以通过 draggable 属性和相关事件实现拖拽功能。 <template> &l…

vue实现socket

vue实现socket

Vue 中实现 WebSocket 通信 在 Vue 项目中实现 WebSocket 通信可以通过原生 WebSocket API 或第三方库(如 socket.io-client)完成。以下是两种常…

vue实现排序

vue实现排序

Vue 实现排序的方法 在 Vue 中实现排序可以通过多种方式完成,以下是一些常见的方法: 使用计算属性排序数组 计算属性非常适合对数据进行排序,因为它会在依赖的数据变化时自动更新。以下是一个示例:…

vue实现datalist

vue实现datalist

使用 Vue 实现 HTML5 的 datalist 功能 HTML5 的 <datalist> 元素提供了一种自动完成输入框的功能,允许用户在输入时从预定义的选项列表中选择。以下是几种在…