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

不用vue实现spa

// 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中实现前端分页通常涉及数据分割和页面控制逻辑。以下是常见的实现方式: 使用计算属性分页 通过计算属性对数据进行切片处理: computed: { paginatedD…

vue功能实现

vue功能实现

Vue 功能实现指南 Vue.js 是一个渐进式 JavaScript 框架,广泛用于构建用户界面。以下是 Vue 功能的常见实现方法。 数据绑定 Vue 的核心功能之一是数据绑定,通过 v-mod…

vue实现路由

vue实现路由

Vue 路由的实现方法 Vue 路由可以通过 Vue Router 库来实现,Vue Router 是 Vue.js 官方的路由管理器,用于构建单页面应用(SPA)。 安装 Vue Router 通…

vue实现toggle

vue实现toggle

Vue 实现 Toggle 功能 在 Vue 中实现 toggle(切换)功能可以通过多种方式完成,以下是几种常见的方法: 使用 v-model 和 v-on 通过 v-model 绑定数据,结合…

vue 实现筛选

vue 实现筛选

实现筛选功能的基本方法 在Vue中实现筛选功能通常涉及以下几个核心步骤: 数据绑定与筛选逻辑 使用v-model绑定筛选条件到Vue实例的数据属性,结合计算属性实现动态筛选: data() {…

vue实现上传

vue实现上传

Vue 文件上传实现方法 使用 Vue 实现文件上传可以通过原生 HTML5 的 <input type="file"> 元素结合 Vue 的事件处理和数据绑定来实现。 基础实现步骤…