上一篇
传统页面跳转就像"每次点餐都要换家餐厅":
点击链接 → 服务器返回完整HTML → 浏览器重绘整个页面
💔 痛点:白屏等待、表单数据丢失、动画中断
// 1. 拦截所有链接点击 document.addEventListener('click', function(e) { if (e.target.tagName === 'A') { e.preventDefault(); loadPage(e.target.href); } }); // 2. Ajax加载页面内容 function loadPage(url) { const xhr = new XMLHttpRequest(); xhr.open('GET', url); xhr.onload = function() { if (xhr.status === 200) { document.getElementById('app').innerHTML = xhr.responseText; // 3. 更新浏览器历史 history.pushState(null, null, url); } }; xhr.send(); } // 4. 监听浏览器前进/后退 window.addEventListener('popstate', function() { loadPage(location.pathname); });
// router.js import { createRouter, createWebHistory } from 'vue-router'; const routes = [ { path: '/', component: () => import('./Home.vue') }, { path: '/about', component: () => import('./About.vue') } ]; const router = createRouter({ history: createWebHistory(), routes }); // App.vue <template> <router-view v-if="isRouterAlive"></router-view> </template> <script setup> import { provide, ref } from 'vue'; const isRouterAlive = ref(true); provide('reload', () => { isRouterAlive.value = false; nextTick(() => isRouterAlive.value = true); }); </script>
特性 | Hash模式 | History模式 |
---|---|---|
URL示例 | /page#about |
/page/about |
兼容性 | IE8+ | IE10+ |
SEO友好度 | 🔴 差 | 🟢 优 |
配置难度 | 🟢 简单 | 🔴 需服务器配合 |
加载状态提示
xhr.onprogress = function(e) { const percent = (e.loaded / e.total) * 100; document.getElementById('progress').style.width = percent + '%'; };
📊 效果:进度条实时显示加载进度
缓存优化
// 浏览器缓存30分钟 const cachedData = localStorage.getItem('pageCache:' + url); if (cachedData && Date.now() - JSON.parse(cachedData).timestamp < 1800000) { renderPage(JSON.parse(cachedData).html); } else { fetchData(); }
错误处理
xhr.onerror = function() { document.getElementById('app').innerHTML = ` <div class="error"> <h2>🚨 加载失败</h2> <button onclick="location.reload()">重试</button> </div> `; };
Q:移动端点击延迟怎么办?
A:添加CSS属性解决300ms延迟:
html { touch-action: manipulation; }
Q:如何实现动画过渡?
A:结合CSS transitions:
.page-enter-active, .page-leave-active { transition: all 0.5s ease; } .page-enter, .page-leave-to { opacity: 0; transform: translateX(30px); }
GitHub开源地址
🎯 支持:Vue3/React18/Svelte4多框架对比
📊 数据来源:2025年8月最新技术文档/GitHub热榜项目/Vue/React官方更新日志
🌟 收藏备用:下次做SPA项目时,这篇攻略能帮你节省80%的调试时间!
本文由 业务大全 于2025-08-26发表在【云服务器提供商】,文中图片由(业务大全)上传,本平台仅提供信息存储服务;作者观点、意见不代表本站立场,如有侵权,请联系我们删除;若有图片侵权,请您准备原始证明材料和公证书后联系我方删除!
本文链接:https://cloud.7tqx.com/wenda/737634.html
发表评论