# [Nuxt] Nuxt 3 - Plugins ###### tags: `Nuxt` ## 特性 * 可在檔名加上 `.server` 或 `.client` 來決定在哪一端載入 plugin * 範例:`hello.server.ts`、`hello.client.ts` * 若出現 `window / document is not defined`,是因為 server 端沒有這些 API,這時可在檔名加上 `.client`,只在 client 端載入插件 * 自動註冊,不需在 `nuxt.config` 內設定 * 只有在資料夾下第一層及子資料夾內的 index 才會自動註冊 * 創建 plugin ```javascript export default defineNuxtPlugin((nuxtApp) => { // ... }) ``` * 若想設定更多選項,可以採用 object 語法。[官方文件](https://nuxt.com/docs/guide/directory-structure/plugins#object-syntax-plugins) * 可以透過在檔名前加上編號指定 plugin 的註冊順序 * 範例:`01.pluginA.js`、`02.pluginB.js` * 插件內可以使用 composables * 若 composable 有使用其他 plugin,要留意 plugin 註冊順序 * 使用的 composable 不能用 Vue.js lifecycle,因為它會被綁定到當前 component,而 plugin 只被綁定到 `nuxtApp`, ## 寫法 ### Automatically Providing Helpers ```javascript export default defineNuxtPlugin((nuxtApp) => { return { provide: { hello: (msg) => `Hello ${msg}`, }, }; }); ``` ```javascript <script setup> const { $hello } = useNuxtApp(); </script> ``` ```htmlmixed <template> <p>{{ $hello('world') }}</p> </template> ``` ### Vue Plugins 使用情境:有支援 Vue 3,但未支援 Nuxt 3 的套件 ```javascript import VCalendar from 'v-calendar'; import 'v-calendar/style.css'; export default defineNuxtPlugin((nuxtApp) => { nuxtApp.vueApp.use(VCalendar, {}); }); ``` ```javascript <script setup> const selectedDate = ref(new Date()); </script> ``` ```htmlmixed <template> <VDatePicker v-model='selectedDate' /> </template> ``` ### Vue Directives ```javascript import dayjs from 'dayjs'; export default defineNuxtPlugin((nuxtApp) => { nuxtApp.vueApp.directive('timeFormat', { mounted(el, binding) { const result = dayjs(binding.value).format('YYYY-MM-DD'); el.innerText = result; }, }) }); ``` ```javascript <script setup> const time = ref(1641034045819); </script> ``` ```htmlmixed <template> <p v-time-format="time"></p> </template> ``` ## 參考資料 * [官方文件](https://nuxt.com/docs/guide/directory-structure/plugins) --- :::info 建立日期:2023-08-29 更新日期:2023-08-29 :::
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up