透過超過 100 個技巧的集合學習 Nuxt!

utils

使用 utils/ 目錄來在整個應用程式中自動導入您的實用函式。

utils/ 目錄的主要目的是允許您的 Vue 組合式函式和其他自動導入的實用函式之間有語義上的區別。

用法

方法 1: 使用具名匯出

utils/index.ts
export const { 
format
:
formatNumber
} =
Intl
.
NumberFormat
('en-GB', {
notation
: 'compact',
maximumFractionDigits
: 1
})

方法 2: 使用預設匯出

utils/random-entry.ts 或 utils/randomEntry.ts
// It will be available as randomEntry() (camelCase of file name without extension)
export default function (
arr
:
Array
<any>) {
return
arr
[
Math
.
floor
(
Math
.
random
() *
arr
.
length
)]
}

您現在可以在 .js.ts.vue 檔案中使用自動導入的實用函式

app.vue
<template>
  <p>{{ formatNumber(1234) }}</p>
</template>
文件 > 指南 > 概念 > 自動導入 中閱讀更多資訊。
文件 > 範例 > 功能 > 自動導入 中閱讀和編輯一個即時範例。
utils/ 自動導入的運作方式和掃描方式與 composables/ 目錄相同。
這些實用程式僅在您的應用程式的 Vue 部分中可用。
只有 server/utils 會在 server/ 目錄中自動導入。