当前位置:首页 > 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 从服务器加载内容片段。

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>';

状态管理方案

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

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 等服务器框架实现同构渲染。

不用vue实现spa

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实现本地数据存储

使用 localStorage 或 sessionStorage Vue 中可以直接调用浏览器提供的 localStorage 或 sessionStorage API 进行数据存储。localSto…

vue实现摘要

vue实现摘要

Vue 实现摘要的方法 在 Vue 中实现文本摘要功能通常涉及截取文本的前部分内容并添加省略号。可以通过计算属性、过滤器或自定义指令来实现。 计算属性实现 在 Vue 组件中定义一个计算属性,用于截…

vue实现管道

vue实现管道

Vue 中实现管道(Pipe)功能 在 Vue 中可以通过过滤器(Filters)或计算属性(Computed Properties)实现类似管道的功能,将数据经过多个处理步骤后输出。 使用过滤器(…

分页实现vue

分页实现vue

分页实现(Vue) 在Vue中实现分页功能通常需要结合前端分页逻辑和后端API支持。以下是两种常见的实现方式: 前端分页实现 适用于数据量较小的情况,直接在客户端完成分页逻辑。 <templ…

vue实现表白

vue实现表白

Vue 实现表白页面 使用 Vue 可以快速创建一个动态、交互式的表白页面。以下是一个简单的实现方案: 基础结构 创建一个 Vue 项目或单文件组件,包含以下核心部分: <template&…

vue实现队列

vue实现队列

Vue 实现队列功能 在 Vue 中实现队列功能可以通过多种方式完成,以下是几种常见的方法: 使用数组模拟队列 队列遵循先进先出(FIFO)原则,可以用数组的 push 和 shift 方法模拟入队…