Nuxt 3 是基于 Vue.js 3 的下一代前端框架,专为构建高性能、可扩展的服务器端渲染(SSR)和静态站点生成(SSG)的应用程序而设计。Nuxt 3 引入了许多新特性和改进,使其成为现代 Web 开发的强大工具
在开启 SSR 模式后, 跳转到需要先渲染后加载的页面,会发生路由阻塞,页面会等待整个页面加载完成后, 再进入到页面;对于客户端来说,会产生一种错觉,就是没有进入到该页面,一直卡顿。
解决办法: 添加页面骨架屏
1、书写骨架屏样式
<!-- app.vue -->
<!-- Skeleton -->
<div id="skeleton-wrapper">
正在加载
</div>
<!-- 写骨架屏样式 -->
<style>
#skeleton-wrapper{
width: 100vw;
height: 100vh;
position: fixed;
z-index: 9999;
top: 0;
left: 0;
display: none;
background: #ffffff;
justify-content: center;
align-items: center;
opacity: .93;
&.active{
display: flex;
}
}
</style>
2、使用 nuxtApp.hook 钩子
/** /mixin/nuxt-hooks.ts */
export default defineNuxtPlugin((nuxtApp) => {
nuxtApp.hook("app:created", () => {
// console.log("app:created");
})
nuxtApp.hook("app:mounted", () => {
// console.log("app:mounted");
})
nuxtApp.hook("page:start", () => {
// console.log("page:start");
if (document && document.body) {
const skeleton = document.getElementById("skeleton-wrapper");
if (skeleton) {
skeleton.classList.add("active");
}
}
})
nuxtApp.hook("page:loading:end", () => {
// console.log("page:loading:end");
if (document && document.body) {
const skeleton = document.getElementById("skeleton-wrapper");
if (skeleton) {
skeleton.classList.remove("active");
}
}
})
})
3、挂载 plugins
在 nuxt.config.ts 中写入
export default defineNuxtConfig({
// ......
plugins: [
'~/mixin/nuxt-hooks.ts'
],
// .....
})
致辞当路由阻塞时,会弹出对应的骨架屏占位,提高用户体验。