当前位置:首页 > VUE

不用vue实现spa

2026-01-08 05:58:24VUE

使用原生 JavaScript 实现 SPA

通过监听 URL 变化动态加载内容,结合 history.pushStatehashchange 事件实现路由切换。

// 路由配置
const routes = {
  '/': 'Home Page Content',
  '/about': 'About Page Content',
  '/contact': 'Contact Page Content'
};

// 渲染函数
function render(path) {
  document.getElementById('app').innerHTML = routes[path] || '404 Not Found';
}

// 监听路由变化
window.addEventListener('popstate', () => {
  render(window.location.pathname);
});

// 初始化路由
document.addEventListener('DOMContentLoaded', () => {
  document.body.addEventListener('click', (e) => {
    if (e.target.matches('[data-link]')) {
      e.preventDefault();
      history.pushState(null, null, e.target.href);
      render(window.location.pathname);
    }
  });
  render(window.location.pathname);
});

使用 Hash 路由方案

通过 window.location.hash 的变化实现路由切换,兼容性更好。

// 路由配置
const routes = {
  '#/': 'Home Page Content',
  '#/about': 'About Page Content',
  '#/contact': 'Contact Page Content'
};

// 渲染函数
function render(hash) {
  document.getElementById('app').innerHTML = routes[hash] || '404 Not Found';
}

// 监听 hash 变化
window.addEventListener('hashchange', () => {
  render(window.location.hash);
});

// 初始化
document.addEventListener('DOMContentLoaded', () => {
  if (!window.location.hash) {
    window.location.hash = '#/';
  }
  render(window.location.hash);
});

使用 Page.js 轻量级路由库

引入 Page.js 库简化路由实现,提供更丰富的路由功能。

<script src="https://unpkg.com/page/page.js"></script>
<script>
  page('/', () => {
    document.getElementById('app').innerHTML = 'Home Page';
  });
  page('/about', () => {
    document.getElementById('app').innerHTML = 'About Page';
  });
  page('*', () => {
    document.getElementById('app').innerHTML = '404 Not Found';
  });
  page();
</script>

结合 AJAX 加载动态内容

通过 XMLHttpRequest 或 Fetch API 从服务器加载内容片段。

不用vue实现spa

function loadContent(url) {
  fetch(url)
    .then(response => response.text())
    .then(html => {
      document.getElementById('app').innerHTML = html;
    });
}

window.addEventListener('popstate', () => {
  loadContent(window.location.pathname + '.html');
});

实现组件化架构

通过自定义元素或模板引擎实现组件化开发。

// 定义组件
class MyComponent extends HTMLElement {
  connectedCallback() {
    this.innerHTML = `<div>Component Content</div>`;
  }
}

// 注册组件
customElements.define('my-component', MyComponent);

// 使用组件
document.getElementById('app').innerHTML = '<my-component></my-component>';

状态管理方案

通过全局对象或事件总线实现简单的状态管理。

不用vue实现spa

const store = {
  state: { count: 0 },
  setState(newState) {
    this.state = { ...this.state, ...newState };
    this.notify();
  },
  subscribers: [],
  subscribe(callback) {
    this.subscribers.push(callback);
  },
  notify() {
    this.subscribers.forEach(callback => callback(this.state));
  }
};

// 组件订阅状态变化
store.subscribe(state => {
  document.getElementById('counter').textContent = state.count;
});

性能优化技巧

使用惰性加载和缓存策略提升应用性能。

const componentCache = {};

async function loadComponent(name) {
  if (!componentCache[name]) {
    const response = await fetch(`/components/${name}.html`);
    componentCache[name] = await response.text();
  }
  return componentCache[name];
}

实现路由守卫

通过中间件函数实现路由权限控制。

function authGuard(ctx, next) {
  if (!isLoggedIn() && ctx.path !== '/login') {
    page.redirect('/login');
  } else {
    next();
  }
}

page('/dashboard', authGuard, () => {
  // 受保护的路由
});

服务端渲染支持

通过 Express 等服务器框架实现同构渲染。

const express = require('express');
const app = express();

app.get('*', (req, res) => {
  const html = `
    <html>
      <body>
        <div id="app">${getContentForPath(req.path)}</div>
        <script src="/client.js"></script>
      </body>
    </html>
  `;
  res.send(html);
});

标签: vuespa
分享给朋友:

相关文章

vue实现自定义登录

vue实现自定义登录

实现自定义登录的基本步骤 在Vue中实现自定义登录功能通常需要结合前端和后端技术。以下是一个基本的实现流程: 创建登录表单组件 使用Vue的单文件组件创建一个登录表单,包含用户名和密码输入框以及提交…

vue实现a4打印模板

vue实现a4打印模板

使用Vue实现A4打印模板 在Vue中实现A4打印模板需要结合CSS的打印样式和Vue的模板渲染能力。以下是具体实现方法: 设置A4纸张尺寸 在CSS中定义A4纸张的标准尺寸(210mm × 297…

vue实现token

vue实现token

Vue 中实现 Token 认证的方法 在 Vue 中实现 Token 认证通常涉及前端与后端的交互,包括 Token 的获取、存储、发送和刷新等操作。以下是具体实现步骤: 获取 Token 用户登…

vue实现动画

vue实现动画

Vue 实现动画的方法 Vue 提供了多种方式来实现动画效果,包括内置的过渡系统、第三方动画库以及直接操作 CSS 或 JavaScript 动画。 使用 Vue 内置过渡系统 Vue 的 <…

vue 实现拖拉

vue 实现拖拉

Vue 实现拖拽功能的方法 使用 HTML5 原生拖放 API HTML5 提供了原生的拖放 API,可以通过 draggable 属性、dragstart、dragend、dragover 和 dr…

vue 菜单实现

vue 菜单实现

Vue 菜单实现方法 在Vue中实现菜单功能可以通过多种方式完成,以下是几种常见的实现方法: 使用v-for动态生成菜单 通过数据驱动的方式动态渲染菜单项,适合菜单内容可能变化的场景: <t…