不用vue实现spa
使用原生 JavaScript 实现 SPA
通过 History API 和动态内容加载实现单页应用的核心逻辑。pushState 和 popstate 事件用于管理路由变化,XMLHttpRequest 或 fetch 实现异步内容加载。
// 路由配置
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')()
]
};






