透過 100+ 個技巧的合輯學習 Nuxt!

utils

使用 utils/ 目錄來自動匯入整個應用程式中的工具函式。

utils/ 目錄的主要目的是為了語意化地區分 Vue composables 和其他自動匯入的工具函式。

用法

方法 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/ 目錄中自動匯入。