本篇文章同步更新於個人部落格,歡迎交流指教~謝謝您的閱讀
nuxt-swiper 版本:v1.2.0
網站開發常使用到輪播功能,Swiper 是一款基於 Javascript 開發、功能完整、實用性高的輪播套件,接下來說明在 Nuxt3 專案搭配 nuxt-swiper 實作
使用 Nuxt 整合模組 nuxt-swiper
進行安裝(基於 Swiper Vue)
npm install nuxt-swiper
swiper 配置選項:
// nuxt.config.js
export default defineNuxtConfig({
modules: [
'nuxt-swiper'
],
swiper: {
modules: ['navigation', 'pagination', 'effect-creative' ]
}
})
在頁面上使用元件,範例頁面 pages/swiper.vue
<Swiper>
、<SwiperSlide>
(名稱依照前面設定的 prefix)<SwiperNavigation>
以及 <SwiperPagination>
// pages/swiper.vue
<template>
<div>
<Swiper
:modules="[ SwiperNavigation, SwiperEffectCreative ]"
:slides-per-view="1"
:space-between="16"
:loop="true">
<SwiperSlide>Slide 1</SwiperSlide>
<SwiperSlide>Slide 2</SwiperSlide>
<SwiperSlide>Slide 3</SwiperSlide>
<SwiperSlide>Slide 4</SwiperSlide>
</Swiper>
</div>
</template>
或是將屬性包裝成物件,透過 v-bind
傳入,配置選項較複雜時,能提升模板可讀性
// pages/swiper.vue
<template>
<div>
<Swiper v-bind="swiperConfig">
<SwiperSlide>Slide 1</SwiperSlide>
<SwiperSlide>Slide 2</SwiperSlide>
<SwiperSlide>Slide 3</SwiperSlide>
<SwiperSlide>Slide 4</SwiperSlide>
</Swiper>
</div>
</template>
<script setup>
const swiperConfig = {
modules: [
SwiperNavigation,
SwiperEffectCreative
],
slidesPerView: 1,
spaceBetween: 16,
loop: true,
breakpoints: {
545: {
slidesPerView: 2
},
1080: {
slidesPerView: 3
},
1280: {
slidesPerView: 4
}
}
};
</script>
事件選項參考 官方文件
// pages/swiper.vue
<template>
<div>
<Swiper @slide-change="slideChange()">
...
</Swiper>
</div>
</template>
<script setup>
const slideChange = () => {
console.log('slideChange');
};
</script>
使用 Swiper 預設樣式(樣式選擇)
// import Swiper 與模組樣式
import 'swiper/css';
import 'swiper/css/navigation';
import 'swiper/css/pagination';
useSwiper()
實作控制按鈕使用 Swiper Vue useSwiper()
hook,來取得 Swiper 實體,呼叫相關方法(ex: slidePrev()
)
// components/SwiperController.vue
<template>
<button @click="direction === 'prev' ? swiper.slidePrev() : swiper.slideNext()">
{{ direction }}
</button>
</template>
<script setup>
const props = defineProps({
direction: {
type: String,
default: '',
validator: value => {
return [ 'prev', 'next' ].includes(value);
}
}
});
const swiper = useSwiper();
</script>
// pages/swiper.vue
<template>
<div>
<Swiper>
<SwiperSlide>Slide 1</SwiperSlide>
<SwiperSlide>Slide 2</SwiperSlide>
<SwiperSlide>Slide 3</SwiperSlide>
<SwiperSlide>Slide 4</SwiperSlide>
<SwiperController direction="prev" />
<SwiperController direction="next" />
</Swiper>
</div>
</template>
參考資源:
https://github.com/cpreston321/nuxt-swiper
https://swiperjs.com/vue