Nuxt3 - Components
元件名稱
Nuxt 所自動載入 ./components 目錄下的元件,在使用時的元件名稱也對應著檔案名稱,而當你在巢狀的目錄結構下的元件,元件的名稱將會基於目錄的路徑與檔案名稱,並刪除重複的字段。
舉例來說,如果 ./components 目錄結構如下:
components/
└── base/
└── apply/
└── Button.vue
./components/base/apply/Button.vue 元件的名稱就會是由目錄與檔案名稱組合出的 <BaseApplyButton>。
為了開發上能更清楚辨別,建議將檔案名稱設置與使用元件時的名稱相同,所以我們重新命名 ./components/base/apply/ 下的 Button.vue 為 BaseApplyButton.vue。
components/
└── base/
└── apply/
└── BaseApplyButton.vue
你也不用擔心元件名稱會不會變成 <BaseApplyBaseApplyButton> 看起來有點醜醜的,因為 Nuxt 會幫我們刪除重複的字段,所以在使用時元件名稱為 <BaseApplyButton>。
元件名稱的命名規則
Vue 在註冊元件時,可以使用大駝峰式命名法 (Pascal Case) 或烤肉串命名法 (Kebab Case) 來為元件命名,並在 template 也可以自由使用兩種命名方式作為使用元件的標籤。
例如,以 <base-apply-button> 來表示使用 ./components/base/apply/BaseApplyButton.vue 元件。
抑或建立 ./components/base/apply/base-apply-button.vue 元件,使用時以 <BaseApplyButton> 表示。
兩種方式 Nuxt 都支援,可以根據自己的習慣做選擇,而我個人是以大駝峰式命名法 (Pascal Case) 為主,以此區別為自己建立的元件。
動態元件 (Dynamic Components)
如果想要使用像 Vue 中的 <component :is="someComputedComponent"> 來動態的切換不同的元件,則需要使用 Vue 提供的 resolveComponentVue 方法來進行輔助。
例如:
<template>
<component :is="show ? DynamicComponent : DivComponent" :props="data" />
</template>
<script setup>
const show = ref(false);
const DynamicComponent = resolveComponent("BaseApplyButton");
const DivComponent = resolveComponent("DivComponent");
</script>
建立動態元件
Step 1. 建立元件
新增 ./components/base/apply/BaseApplyButton.vue,內容如下:
<template>
<button type="submit" class="mt-6 bg-blue-600 py-3 px-8 text-xl font-medium text-white hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2">立即報名</button>
</template>
新增 ./components/round/apply/RoundApplyButton.vue,內容如下:
<template>
<button type="submit" class="mt-6 rounded-full bg-blue-600 py-3 px-8 text-xl font-medium text-white hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2">
立即報名
</button>
</template>
Step 2. 使用 resolveComponent()
調整 ./app.vue,內容如下:
<template>
<div class="flex flex-col items-center">
<div class="mt-8 flex items-center">
<input
id="show-button"
v-model="useRound"
name="show-button"
type="checkbox"
class="h-5 w-5"
/>
<label for="show-button" class="ml-2 block text-base text-slate-800">使用圓角按鈕</label>
</div>
<component :is="useRound ? RoundButton : BaseButton" />
</div>
</template>
<script setup>
const useRound = ref(false)
const BaseButton = resolveComponent('BaseApplyButton')
const RoundButton = resolveComponent('RoundApplyButton')
</script>
動態載入 (Dynamic Imports)
動態載入 (Dynamic Imports) 元件也稱之為延遲載入 (lazy-loading),如果頁面中不需要立刻使用或顯示某個元件,透過動態載入的方式可以延遲元件載入的時間點,有助於優化 JavaScript 首次載入時的檔案大小。
使用的方式也非常簡單,只需要在使用元件時,加上前綴 Lazy 就可以有延遲載入的效果。