当前位置:首页 > VUE

不用vue实现spa

2026-03-07 20:32:06VUE

使用原生 JavaScript 实现 SPA

通过监听 URL 变化动态加载内容,结合 history.pushStatehashchange 事件实现路由切换。

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

// 渲染内容到容器
function renderContent(path) {
  const app = document.getElementById('app');
  app.innerHTML = routes[path] || '404 Not Found';
}

// 监听路由变化
window.addEventListener('popstate', () => {
  renderContent(window.location.pathname);
});

// 初始化路由
document.addEventListener('DOMContentLoaded', () => {
  // 拦截链接点击事件
  document.body.addEventListener('click', (e) => {
    if (e.target.tagName === 'A') {
      e.preventDefault();
      const path = e.target.getAttribute('href');
      window.history.pushState({}, '', path);
      renderContent(path);
    }
  });

  // 首次加载
  renderContent(window.location.pathname);
});

使用 History API 管理路由

利用 history.pushStatepopstate 事件实现无刷新页面跳转,URL 显示为干净路径(无 # 符号)。

// 导航函数
function navigate(path) {
  window.history.pushState({}, '', path);
  renderContent(path);
}

// 后退/前进时触发
window.addEventListener('popstate', () => {
  renderContent(window.location.pathname);
});

使用 Hash 路由方案

通过监听 window.onhashchange 事件实现兼容性更好的路由方案,URL 以 #/path 形式呈现。

不用vue实现spa

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

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

// 初始化
window.addEventListener('hashchange', render);
window.addEventListener('load', render);

动态内容加载

结合 AJAX 或 Fetch API 实现按需加载内容,提升性能。

async function loadContent(path) {
  try {
    const response = await fetch(`/api/content?path=${path}`);
    const data = await response.json();
    document.getElementById('app').innerHTML = data.content;
  } catch (error) {
    console.error('Failed to load content:', error);
  }
}

组件化方案

通过自定义元素或模板字符串实现组件化开发,保持代码模块化。

不用vue实现spa

// 定义组件
class MyComponent extends HTMLElement {
  connectedCallback() {
    this.innerHTML = `<div class="component">Component Content</div>`;
  }
}

// 注册组件
customElements.define('my-component', MyComponent);

状态管理方案

使用事件总线或观察者模式实现简单状态管理。

// 简易事件总线
const eventBus = {
  events: {},
  emit(event, data) {
    if (this.events[event]) this.events[event].forEach(cb => cb(data));
  },
  on(event, callback) {
    this.events[event] = this.events[event] || [];
    this.events[event].push(callback);
  }
};

// 使用示例
eventBus.on('data-updated', (data) => {
  console.log('Data changed:', data);
});

性能优化建议

使用 requestAnimationFrame 进行批量 DOM 操作,避免布局抖动。

function batchUpdate(callback) {
  requestAnimationFrame(() => {
    const fragment = document.createDocumentFragment();
    callback(fragment);
    document.getElementById('app').appendChild(fragment);
  });
}

标签: vuespa
分享给朋友:

相关文章

vue实现递归

vue实现递归

Vue 实现递归组件的方法 在 Vue 中实现递归组件通常用于处理树形结构数据(如菜单、评论列表、文件目录等)。以下是具体实现方法: 定义递归组件 通过 name 选项让组件可以递归调用自身:…

vue实现tablegrid

vue实现tablegrid

Vue 实现 TableGrid 的方法 使用 Element UI 的 Table 组件 Element UI 提供了强大的 Table 组件,可以快速实现表格布局。安装 Element UI 后,…

vue diff实现

vue diff实现

Vue Diff 算法实现原理 Vue 的虚拟 DOM Diff 算法(即 patch 过程)是其高效渲染的核心,主要通过对比新旧虚拟节点的差异,最小化 DOM 操作。以下是关键实现要点: 同层级比…

vue 绑定实现

vue 绑定实现

Vue 绑定实现 Vue 提供了多种数据绑定的方式,包括文本插值、属性绑定、事件绑定、双向绑定等。以下是常见的绑定实现方法: 文本插值 使用双大括号 {{ }} 进行文本插值,将数据动态渲染到 DO…

vue实现多选

vue实现多选

Vue 实现多选功能 在 Vue 中实现多选功能可以通过多种方式完成,以下是常见的几种方法: 使用 v-model 绑定数组 通过 v-model 绑定到一个数组,可以实现多选功能。适用于复选框组(…

vue nexttrick实现

vue nexttrick实现

Vue 中 nextTick 的实现原理 nextTick 是 Vue 提供的一个异步方法,用于在下次 DOM 更新循环结束之后执行延迟回调。它利用了 JavaScript 的事件循环机制,确保回调在…