前端開發
Nuxt Layout 使用方式(Nuxt 2)
記錄在 Nuxt 2 的 layouts 資料夾新增一份自訂版面、頁面用 layout 屬性指定要套用哪個版面的做法,範例是一個包含 GSAP 動畫套件與 Font Awesome 圖示的版面。Nuxt 3 之後改用 definePageMeta 指定 layout,寫法不同。
W
Nuxt 2 的 Layout(版面)機制讓不同頁面套用不同的外層骨架(例如某些頁面有側邊欄、某些頁面全螢幕沒有導覽列),這篇記使用方式。
新增自訂 Layout
在 layouts/ 資料夾新增一個 .vue 檔案,結構可以參照專案本來就有的 default.vue:
<!-- layouts/animation.vue -->
<template>
<div>
<nuxt />
</div>
</template>
<script>
export default {
data() {
return {};
},
};
</script>
<nuxt /> 是 Nuxt 2 的固定寫法,代表「目前這個頁面的內容要渲染在這裡」,版面裡其他部分(導覽列、頁尾、動畫背景……)就自由加在 <nuxt /> 的周圍。
在頁面裡指定要用哪個 Layout
<!-- pages/animation-page.vue -->
<template>
<div>
<SquareMonster />
</div>
</template>
<script>
import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome';
import { gsap } from 'gsap/dist/gsap';
import { ScrollToPlugin } from 'gsap/dist/ScrollToPlugin';
import CardAnimation from '~/components/CardAnimation';
import SquareMonster from '~/components/SquareMonster';
gsap.registerPlugin(ScrollToPlugin);
export default {
layout: 'animation',
components: { CardAnimation, SquareMonster },
data() {
return {};
},
mounted() {},
methods: {},
};
</script>
export default 裡的 layout: 'animation' 這個屬性,值對應到 layouts/animation.vue 的檔名(不含副檔名)——這樣這個頁面就會套用剛剛新建的版面,而不是預設的 default.vue。
後來 Nuxt 指定 Layout 的方式改了,layout 屬性換成 definePageMeta,完整寫法整理在《Nuxt 3 專案建立筆記》的 Layout 段落。範例裡用到的 gsap.registerPlugin(ScrollToPlugin) 這行,是 GSAP 3 之後的外掛註冊方式,完整寫法整理在《GSAP 3 遷移筆記》。