Nuxt3 开发技巧

907 阅读3分钟

懒加载组件

并非所有组件都需要立即加载。使用 Nuxt,我们可以通过添加 Lazy 作为前缀来延迟加载。

<!-尽快加载 -->
<Modal v-if="showModal" />

<!-只有当 showModal = true 时加载 -->
<LazyModal v-if="showModal" />

用 Nitro 预渲染特定路由

通过直接配置 Nitro,我们可以只对某些路由进行预渲染。其他所有路由都将像普通路由一样使用混合渲染。

export default defineNuxtConfig({
  nitro: {
    prerender: {
      routes: ['/about', '/blog'],
    },
  },
});

使用内置键值存储

在 Nuxt 中,我们可以使用简单但功能强大的内置键值存储

const storage = useStorage();
const key = `session:token`;

// 保存值
await storage.setItem(key, sessionToken);

// …并在不同接口中调用
const token = await storage.getItem(key);

自动导入

使用 composables/ 目录将您的 Vue 可组合项自动导入到您的应用程序中。

//方法一: 使用命名导出 composables/useFoo.ts
export function useFoo() {
  return useState('foo', () => 'bar')
}

//方法二: 使用默认导出 composables/use-foo.ts or composables/useFoo.ts
// 它将作为 useFoo() 提供(不带扩展名的文件名的驼峰式大小写)
export default function () {
  return useState('foo', () => 'bar')
}

//用法
<script setup>
const bar = useFoo()
//修改
bar.value = 'baz'
</script>

<template>
  <div>
    {{ foo }}
  </div>
</template>

反应式控制头部脚本

Nuxt 3 允许开发人员使用 useHead 可组合功能对应用程序的 进行反应式控制。这样就可以使用动态 titleTemplate 或动态脚本标签。

useHead({
  titleTemplate: (title) => `${title} | My Website`,
  script: [
    {
       src: 'https://www.scripts.com/some/other/script.js',
       body: true
     }
  ]
})

快速获取路由信息

Nuxt3 中的 useRoute 可组合功能可轻松从路由和查询参数中获取信息。

const route = useRoute();

console.log(route.fullPath);
// https://www.website.com/?search=hello%20there

console.log(route.query.search);
// there

轻松处理客户端错误

使用 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>

嵌套路由(又称子路由)

Nuxt 使用 NuxtPage 组件来呈现应用程序 pages/ 目录中的页面。

// pages/one/two/three.vue
<template>
  <!-这个嵌套的 NuxtPage 渲染子路由 -->
  <NuxtPage />
</template>

/assets 与 /public - 如何决定

如果资产需要处理、经常变化且不需要特定的文件名,请选择 assets 文件夹。否则,请使用 public 目录。

从assets文件夹导入资产时,捆绑程序会处理文件,生成带有哈希值的新文件名,并用新文件名替换导入文件。

~/public文件夹适用于无需处理的资产,应直接从应用程序根目录提供。该文件夹中的文件不会被修改,会直接复制到构建输出中。

// 使用 ~/assets
<script setup>
import image from '~/assets/image.png';
import style from '~/assets/style.css';

</script>
<template>
  <img :src="image" />
</template>

// 使用 ~/public
<template>
  <img src="/image.png" />
</template>

使用 appConfig

app.config 用于公开可在构建时确定的公共变量,如主题变体、标题或其他非敏感项目配置。这些值在 app.config.ts 文件中设置。

// app.config.ts
export default defineAppConfig({
  theme: {
    primaryColor: '#ababab'
  }
})

//要访问应用程序中的 app. config 的值,您可以使用可组合 useAppConfig
<script setup lang="ts">
const appConfig = useAppConfig()
</script>

//虽然 appConfig 类型是自动推断的,但如果确实需要,您可以使用 TypeScript 手动键入 app.config。
// index.d.ts
declare module 'nuxt/schema' {
  interface AppConfig {
    // 这将完全取代现有的推断“主题”属性
    theme: {
      // 您可能希望键入此值以添加比Nuxt推断的更具体的类型,
      // 例如字符串文字类型
      primaryColor?: 'red' | 'blue'
    }
  }
}

代码执行环境

默认情况下,Nuxt 3 将在服务器上运行,但您也可以在客户端上运行代码。

// 服务器端
if (process.server) {
  // 执行服务器端代码
}

// 客户端端
if (process.client) {
  // 执行客户端端代码
}