shared

使用 shared/ 目錄在 Vue 應用和 Nitro 伺服器之間共享功能。

shared/ 目錄允許您共享可在 Vue 應用和 Nitro 伺服器中使用的程式碼。

shared/ 目錄在 Nuxt v3.14+ 中可用。
shared/ 目錄中的程式碼不能匯入任何 Vue 或 Nitro 程式碼。

使用

方法一: 命名匯出

shared/utils/capitalize.ts
export const capitalize = (input: string) => {
  return input[0] ? input[0].toUpperCase() + input.slice(1) : ''
}

方法二: 預設匯出

shared/utils/capitalize.ts
export default function (input: string) {
  return input[0] ? input[0].toUpperCase() + input.slice(1) : ''
}

您現在可以在 Nuxt 應用和 server/ 目錄中使用自動匯入的工具。

app/app.vue
<script setup lang="ts">
const hello = capitalize('hello')
</script>

<template>
  <div>
    {{ hello }}
  </div>
</template>
server/api/hello.get.ts
export default defineEventHandler((event) => {
  return {
    hello: capitalize('hello'),
  }
})

檔案如何被掃描

只有 shared/utils/shared/types/ 目錄中的檔案會自動匯入。這些目錄下子目錄中的檔案不會自動匯入,除非您將這些目錄新增到 imports.dirsnitro.imports.dirs

shared/utilsshared/types 自動匯入的工作方式和掃描方式與 app/composables/app/utils/ 目錄相同。
請參閱 文件 > 4 X > 指南 > 目錄結構 > 應用 > 可組合項#檔案如何被掃描 以瞭解更多資訊。
目錄結構
-| shared/
---| capitalize.ts        # Not auto-imported
---| formatters
-----| lower.ts           # Not auto-imported
---| utils/
-----| lower.ts           # Auto-imported
-----| formatters
-------| upper.ts         # Not auto-imported
---| types/
-----| bar.ts             # Auto-imported

您在 shared/ 資料夾中建立的任何其他檔案必須使用 #shared 別名(由 Nuxt 自動配置)手動匯入

// For files directly in the shared directory
import capitalize from '#shared/capitalize'

// For files in nested directories
import lower from '#shared/formatters/lower'

// For files nested in a folder within utils
import upper from '#shared/utils/formatters/upper'

此別名可確保您的應用程式中匯入的一致性,無論匯入檔案位於何處。

文件 > 4 X > 指南 > 概念 > 自動匯入中瞭解更多資訊。