当前位置:首页 > 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中实现贴图功能通常涉及将图片动态添加到指定位置或元素上。以下是几种常见实现方式: 使用v-bind动态绑定图片 通过数据驱动的方式动态更换图片源: <templ…

vue 指令实现

vue 指令实现

Vue 指令实现 Vue 指令是 Vue.js 提供的特殊属性,用于在 DOM 元素上添加特殊行为。指令以 v- 前缀开头,例如 v-model、v-if、v-for 等。以下是实现自定义指令和常用内…

vue实现公式

vue实现公式

在Vue中实现公式展示或计算可以通过多种方式实现,以下为具体方法: 使用模板插值与计算属性 若公式较简单,可直接在模板中使用插值表达式或计算属性。例如计算圆的面积: <template>…

vue实现modal

vue实现modal

Vue 实现 Modal 弹窗组件 使用 Vue 实现 Modal 弹窗组件可以通过多种方式,包括原生 Vue 组件、第三方库或自定义指令。以下是几种常见方法: 原生 Vue 组件实现 创建一个基础…

vue实现插件

vue实现插件

Vue 插件实现方法 Vue 插件通常用于为 Vue 应用添加全局功能或共享功能。以下是实现 Vue 插件的核心步骤: 插件基本结构 Vue 插件需要暴露一个 install 方法,该方法接收 Vu…

vue如何实现计算

vue如何实现计算

Vue 实现计算的方法 Vue 提供了多种方式来实现计算逻辑,包括计算属性、方法、侦听器等。以下是几种常见的实现方式: 计算属性(Computed Properties) 计算属性是基于它们的响应式…