当前位置:首页 > 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 的基础功能。

不用vue实现spa

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 性能,路由切换时仅更新变化的部分。

不用vue实现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')()
  ]
};

标签: vuespa
分享给朋友:

相关文章

vue实现组件循环

vue实现组件循环

Vue 组件循环的实现方法 在 Vue 中实现组件循环通常使用 v-for 指令,可以循环渲染数组或对象的数据到组件上。 基本数组循环 通过 v-for 指令遍历数组,渲染多个相同结构的组件。…

vue实现条件判断

vue实现条件判断

Vue 条件判断实现方法 Vue 提供了多种方式实现条件判断,可以根据不同场景选择合适的方式。 v-if / v-else-if / v-else 这是 Vue 中最常用的条件渲染指令,根据表达式的…

vue实现好友列表

vue实现好友列表

实现好友列表的Vue组件 数据准备 在Vue组件的data中定义好友列表数据,通常是一个数组对象,每个对象包含好友的基本信息如ID、头像、昵称等。 data() { return {…

在线脑图 vue 实现

在线脑图 vue 实现

在线脑图 Vue 实现方案 使用开源库实现 推荐使用 mind-elixir 或 jsmind 这类开源库,它们专为脑图设计且支持 Vue 集成。 安装依赖: npm install mi…

vue播放倍速怎么实现

vue播放倍速怎么实现

实现Vue播放倍速的方法 在Vue中实现播放倍速功能通常涉及HTML5的<video>元素或第三方播放器库。以下是几种常见实现方式: 使用原生HTML5 video元素 通过ref获取…

vue实现按卡片轮播

vue实现按卡片轮播

实现卡片轮播的基本思路 在Vue中实现卡片轮播可以通过结合v-for指令和动态样式绑定完成。核心是维护一个当前显示卡片的索引,通过CSS过渡效果实现平滑切换。 基础实现步骤 模板部分 使用v-fo…