shared
使用 shared/ 目錄來分享 Vue 應用程式和 Nitro 伺服器之間的功能。
shared/
目錄讓您可以分享可在 Vue 應用程式和 Nitro 伺服器中使用的程式碼。
shared/
目錄在 Nuxt v3.14+ 版本中可用。shared/
目錄中的程式碼無法匯入任何 Vue 或 Nitro 程式碼。用法
方法 1: 使用具名匯出
shared/utils/capitalize.ts
export const capitalize = (input: string) => {
return input[0] ? input[0].toUpperCase() + input.slice(1) : ''
}
方法 2: 使用預設匯出
shared/utils/capitalize.ts
export default function capitalize (input: string) {
return input[0] ? input[0].toUpperCase() + input.slice(1) : ''
}
用法: 您現在可以在 Vue 應用程式和 server/
目錄中的 .js
、.ts
和 .vue
檔案中使用自動匯入的工具函數。
如果您已在您的 nuxt.config.ts
中設定 compatibilityVersion: 4
,則可以在 app/
目錄中使用自動匯入的函數。這是 Nuxt 逐步相容功能的一部分,為版本 4 做準備。
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/
目錄中的檔案會被自動匯入。這些目錄的子目錄中的巢狀檔案不會被自動匯入。
目錄結構
-| 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.d.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'
無論匯入檔案的位置為何,此別名可確保在您的應用程式中進行一致的匯入。