当前位置:首页 > VUE

不用vue实现spa

2026-01-14 03:57:42VUE

使用原生 JavaScript 实现 SPA

通过 History API 和动态内容加载实现单页应用的核心逻辑。pushStatepopstate 事件用于管理路由变化,XMLHttpRequestfetch 实现异步内容加载。

// 路由配置
const routes = {
  '/': 'home.html',
  '/about': 'about.html',
  '/contact': 'contact.html'
};

// 动态加载内容
function loadContent(url) {
  fetch(url)
    .then(response => response.text())
    .then(html => {
      document.getElementById('app').innerHTML = html;
    });
}

// 路由变化处理
window.addEventListener('popstate', () => {
  const path = window.location.pathname;
  loadContent(routes[path] || '404.html');
});

// 初始化路由
document.addEventListener('DOMContentLoaded', () => {
  document.body.addEventListener('click', e => {
    if (e.target.matches('[data-link]')) {
      e.preventDefault();
      const href = e.target.getAttribute('href');
      history.pushState(null, null, href);
      loadContent(routes[href]);
    }
  });
  // 加载初始路由
  const initialPath = window.location.pathname;
  loadContent(routes[initialPath] || 'home.html');
});

使用 Web Components 封装组件

通过 Custom Elements 和 Shadow DOM 创建可复用的组件,模拟 Vue 的组件化开发体验。

class MyComponent extends HTMLElement {
  constructor() {
    super();
    this.attachShadow({ mode: 'open' });
    this.shadowRoot.innerHTML = `
      <style>
        :host { display: block; }
        .component { color: blue; }
      </style>
      <div class="component">
        <slot></slot>
      </div>
    `;
  }
}
customElements.define('my-component', MyComponent);

状态管理方案

采用发布-订阅模式实现简单状态管理,类似 Redux 的基础功能。

class Store {
  constructor(state) {
    this.state = state;
    this.subscribers = [];
  }

  subscribe(callback) {
    this.subscribers.push(callback);
  }

  setState(newState) {
    this.state = { ...this.state, ...newState };
    this.subscribers.forEach(cb => cb(this.state));
  }
}

// 使用示例
const store = new Store({ count: 0 });
store.subscribe(state => {
  document.getElementById('counter').textContent = state.count;
});

document.getElementById('increment').addEventListener('click', () => {
  store.setState({ count: store.state.count + 1 });
});

模板渲染引擎

实现简单的模板渲染功能,支持数据绑定和条件渲染。

function render(template, data) {
  return template.replace(/\{\{(\w+)\}\}/g, (_, key) => {
    return data[key] || '';
  });
}

// 使用示例
const template = '<div>{{title}}</div><p>{{content}}</p>';
const data = { title: 'Hello', content: 'World' };
document.getElementById('app').innerHTML = render(template, data);

性能优化策略

采用惰性加载和缓存机制提升 SPA 性能,路由切换时仅更新变化的部分。

const cache = {};
async function loadContentCached(url) {
  if (cache[url]) return cache[url];
  const response = await fetch(url);
  const html = await response.text();
  cache[url] = html;
  return html;
}

路由守卫实现

通过路由拦截实现权限控制,类似 Vue Router 的导航守卫功能。

const auth = {
  isAuthenticated: false
};

function navigateTo(path) {
  if (path === '/admin' && !auth.isAuthenticated) {
    history.pushState(null, null, '/login');
    return loadContent('login.html');
  }
  history.pushState(null, null, path);
  loadContent(routes[path]);
}

构建工具集成

使用 Rollup 或 Webpack 打包原生 JavaScript SPA,支持代码分割和 tree-shaking。

// rollup.config.js
export default {
  input: 'src/main.js',
  output: {
    dir: 'dist',
    format: 'es'
  },
  plugins: [
    require('rollup-plugin-node-resolve')(),
    require('rollup-plugin-commonjs')()
  ]
};

不用vue实现spa

标签: vuespa
分享给朋友:

相关文章

vue伪函数实现

vue伪函数实现

Vue 伪函数实现方法 伪函数(Mock Function)在 Vue 中常用于测试或模拟某些逻辑,以下是几种常见的实现方式: 使用 Jest 的 jest.fn() 在单元测试中,可以通过 Jes…

vue表格实现教学

vue表格实现教学

Vue 表格实现方法 使用原生HTML表格 在Vue模板中直接使用HTML的<table>标签,结合v-for动态渲染数据: <template> <table&g…

vue实现放大效果

vue实现放大效果

使用 CSS transform 实现放大效果 在 Vue 中实现放大效果可以通过 CSS 的 transform: scale() 属性。这种方法简单高效,适合大多数交互场景。 定义一个 CSS…

vue实现压缩上传文件

vue实现压缩上传文件

压缩上传文件的实现方法 在Vue中实现文件压缩和上传功能,可以通过以下步骤完成。该方法结合了前端文件压缩库和HTTP请求,确保文件在上传前被有效压缩。 安装必要的依赖 需要使用compressor…

vue实现查询替换

vue实现查询替换

Vue 实现查询替换功能 在 Vue 中实现查询替换功能,可以通过数据绑定和字符串操作方法结合实现。以下是具体实现方式: 基础实现 <template> <div>…

vue实现冰墩墩

vue实现冰墩墩

使用 Vue 实现冰墩墩动画 通过 Vue 的动画特性和 SVG 技术,可以动态渲染冰墩墩的形象。以下是具体实现方法: 准备 SVG 素材 冰墩墩的形象通常由多个 SVG 路径组成,包括身体轮廓…