Nuxt3 踩坑记录
Nuxt3正式版发布已经很久了,实际开发中还是遇到不少问题记录一下。
1. 懒加载组件 #
并非所有组件都需要立即加载。 使用 Nuxt,我们可以通过添加 Lazy 作为前缀来延迟加载。 Nuxt 会为我们完成所有繁重的工作!
<!-- 尽快加载 -->
<Modal v-if="showModal" />
<!-- 只有当 showModal = true 时加载 -->
<LazyModal v-if="showModal" />
2. 用 Nitro 预渲染特定路由 #
通过直接配置 Nitro,我们可以只对某些路由进行预渲染。 其他所有路由都将像普通路由一样使用混合渲染:
export default defineNuxtConfig({
nitro: {
prerender: {
routes: ['/about', '/blog']
}
}
})
3. 使用内置键值存储 #
在 Nuxt 中,我们可以使用简单但功能强大的内置键值存储:
const storage = useStorage()
const key = 'session:token'
// 保存值
await storage.setItem(key, sessionToken)
// …并在不同接口中调用
const token = await storage.getItem(key)
4. 自动导入 #
利用自动导入功能,我们可以快速访问路由和用户信息,而无需手动导入。 这有助于使我们的代码更有条理、更高效、更易读。
<script setup>
// 我们可以使用已导入的路由和用户,而无需自行导入
const { path, params } = useRoute()
const userData = useCustomComposable()
</script>
5. 反应式控制头部脚本 #
Nuxt 3 允许开发人员使用 useHead 可组合功能对应用程序的 进行反应式控制。 这样就可以使用动态 titleTemplate 或动态脚本标签:
useHead({
titleTemplate: (title) => `${title} | My Website`,
script: [
{
src: 'https://www.scripts.com/some/other/script.js',
body: true
}
]
})
6. 快速获取路由信息 #
Nuxt3 中的 useRoute 可组合功能可轻松从路由和查询参数中获取信息。 下面是一个示例:
const route = useRoute()
console.log(route.fullPath)
// https://www.website.com/?search=hello%20there
console.log(route.query.search)
// there
7. 轻松处理客户端错误 #
使用 NuxtErrorBoundary 组件围绕应用程序中不同的功能块,可让您一起处理一组错误,从而提供更好的用户体验。 这样,您就可以在应用程序中包含错误,并以特定的方式处理它们,而不是使用通用的错误页面。
<NuxtErrorBoundary>
<NuxtPage />
<template #error="{ error }">
<div>
<p>
Oh no, something broke when loading the lesson!
<code>{{ error }}</code>
</p>
<p>
<button class="hover:cursor-pointer" @click="clearError(error)">Go to the first lesson</button>
</p>
</div>
</template>
</NuxtErrorBoundary>
8. 嵌套路由(又称子路由) #
Nuxt 使用 NuxtPage 组件来呈现应用程序 pages/ 目录中的页面。 添加嵌套的 NuxtPage 组件可让你匹配文件夹层次结构中的多个页面,从而实现更灵活的路由:
// pages/one/two/three.vue
<template>
<!-这个嵌套的 NuxtPage 渲染子路由 -->
<NuxtPage />
</template>
Nuxt 中的嵌套路由可视为文件夹层次结构,有助于组织和结构化应用程序。
例如,路由 /one/two/three 相当于这种文件夹结构:
one/ - two/ - - three/
9. /assets 与 /public - 如何决定? #
Nuxt 3 为管理网络程序中的资产提供了两种选择:
- ~/assets 文件夹
- ~/public 文件夹 如果资产需要处理、经常变化且不需要特定的文件名,请选择
assets文件夹。 否则,请使用public目录。 // 使用 ~/assets
<script setup>
import image from '~/assets/image.png'
</script>
<template>
<img :src="image" />
</template>
// 使用 ~/public
<template>
<img src="/image.png" />
</template>
10. 使用 /assets 目录 #
Nuxt 3 中的 ~/assets 文件夹适用于需要处理的资产。 例如,图像、样式表、图标和字体。 从该文件夹导入资产时,捆绑程序会处理文件,生成带有哈希值的新文件名,并用新文件名替换导入文件。
import image from '~/assets/image.png'
import style from '~/assets/style.css'
~/assets 文件夹还有一个好处,就是可以在构建过程中捕捉丢失的资产。如果资产丢失,就会出现构建错误,这有助于维护应用程序的完整性。而 ~/public 文件夹中的资产不会出现这种情况,因为它们不会被处理。
// 从 `~/assets` 导入时会发现丢失的资产
;`import missingImage from '~/assets/missing-image.png'; `
// 构建错误
// 从 ~/public 引用不会捕获丢失的资产
// 在模板中: <img src="/missing-image.png" />
// 不会构建错误
11. 使用 /public 目录 #
~/public文件夹适用于无需处理的资产,应直接从应用程序根目录提供。 该文件夹中的文件不会被修改,会直接复制到构建输出中。
// 从 ~/public 访问文件
yourwebsite.com/robots.txt
yourwebsite.com/favicon.ico
yourwebsite.com/sitemap.xml