当前位置:首页 > 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 形式呈现。

// 路由配置
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);
  }
}

组件化方案

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

// 定义组件
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 操作,避免布局抖动。

不用vue实现spa

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

标签: vuespa
分享给朋友:

相关文章

vue实现网页切换

vue实现网页切换

Vue 实现网页切换的方法 在 Vue 中实现网页切换通常可以通过以下几种方式完成,具体取决于项目需求和路由管理方式。 使用 Vue Router Vue Router 是 Vue.js 官方提供的…

computed vue 实现

computed vue 实现

computed 在 Vue 中的基本用法 Vue 的 computed 属性用于声明依赖于其他数据的计算属性。当依赖的数据变化时,计算属性会自动重新计算并缓存结果。 export defaul…

vue实现树

vue实现树

Vue 实现树形结构的方法 使用递归组件实现树形结构 递归组件是Vue中实现树形结构的常见方式。通过组件调用自身,可以轻松构建多层嵌套的树形数据。 <template> <ul…

vue实现开关

vue实现开关

Vue 实现开关组件的方法 使用原生HTML和Vue数据绑定 通过v-model绑定复选框的checked状态,结合CSS样式实现开关效果: <template> <label…

vue实现portal

vue实现portal

Vue 实现 Portal 功能 Portal 是一种将子节点渲染到父组件 DOM 层级之外的 DOM 节点的技术,常用于实现模态框、弹出层等需要脱离当前组件层级的场景。Vue 可以通过多种方式实现…

vue监听实现

vue监听实现

Vue 监听实现方法 在 Vue 中可以通过多种方式实现监听数据变化或事件触发,以下是常见的几种方法: 使用 watch 选项 watch 是 Vue 提供的核心功能之一,用于观察和响应 Vue 实…