👆建議你可以使用影片子母畫面功能或全螢幕播放來獲得最佳的觀賞體驗,👇下方是本篇教學的相關筆記。
安裝 Vue Scrollto 套件
npm install -D vue-scrollto
在 puglins 目錄下建立一個檔案 ./plugins/scrollto.js:
import VueScrollTo from 'vue-scrollto'
export default defineNuxtPlugin((nuxtApp) => {
nuxtApp.vueApp.use(VueScrollTo)
})
修改 app.vue 檔案:
<template>
<div class="flex flex-col items-center overflow-y-visible px-6 py-4">
<a v-scroll-to="'#element'" href="#" class="my-4 font-medium text-gray-600">
捲動頁面至 #element
</a>
<div id="element" class="mt-24">
<h1 class="p-2 text-6xl font-semibold text-sky-400">這裡是 #element</h1>
</div>
<div class="h-screen w-full"></div>
</div>
</template>
修改 ./plugins/scrollto.js 檔案,回傳 provide 與函式:
import VueScrollTo from 'vue-scrollto'
export default defineNuxtPlugin((nuxtApp) => {
nuxtApp.vueApp.use(VueScrollTo)
return {
provide: {
scrollTo: VueScrollTo.scrollTo
}
}
})
修改 app.vue 檔案,添加按鈕與實作函式呼叫 helper:
<template>
<div class="flex flex-col items-center overflow-y-visible px-6 py-4">
<a v-scroll-to="'#element'" href="#" class="my-4 font-medium text-gray-600">
捲動頁面至 #element
</a>
<button
class="my-4 w-fit rounded-full bg-blue-500 px-8 py-3 font-medium text-white hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2"
@click="scrollToElement"
>
捲動頁面至 #element
</button>
<div id="element" class="mt-24">
<h1 class="p-2 text-6xl font-semibold text-sky-400">這裡是 #element</h1>
</div>
<div class="h-screen w-full"></div>
</div>
</template>
<script setup>
const scrollToElement = () => {
useNuxtApp().$scrollTo('#element')
}
</script>
在 puglins 目錄下建立一個檔案 ./plugins/directive.js:
export default defineNuxtPlugin((nuxtApp) => {
nuxtApp.vueApp.directive('focus', {
mounted(el) {
el.focus()
}
})
})
修改 app.vue 檔案,在按鈕上添加 v-focus
指令:
<template>
<div class="flex flex-col items-center overflow-y-visible px-6 py-4">
<a v-scroll-to="'#element'" href="#" class="my-4 font-medium text-gray-600">
捲動頁面至 #element
</a>
<button
v-focus
class="my-4 w-fit rounded-full bg-blue-500 px-8 py-3 font-medium text-white hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2"
@click="scrollToElement"
>
捲動頁面至 #element
</button>
<div id="element" class="mt-24">
<h1 class="p-2 text-6xl font-semibold text-sky-400">這裡是 #element</h1>
</div>
<div class="h-screen w-full"></div>
</div>
</template>
<script setup>
const scrollToElement = () => {
useNuxtApp().$scrollTo('#element')
}
</script>
感謝大家的閱讀,歡迎大家給予建議與討論,也請各位大大鞭小力一些:)
如果對這個 Nuxt 3 系列感興趣,可以訂閱
接收通知,也歡迎分享給喜歡或正在學習 Nuxt 3 的夥伴。
範例程式碼
參考資料