一、背景
nuxt3项目使用swiper实现轮播图效果。
二、官网文档
2.1、Swiper CDN
2.2、使用方法
2.3、基础演示
2.4、api
三、项目使用
3.1、nuxt.config.ts引入css、js
link: [
{ rel: 'stylesheet', type: 'text/css', href: 'https://unpkg.com/swiper@8/swiper-bundle.css'}
],
script: [
{
type: 'text/javascript',
src: 'https://unpkg.com/swiper@8/swiper-bundle.js'
}
]
3.2、页面使用
<template>
<div class="container">
<div class="swiper mySwiper">
<div class="swiper-wrapper">
<div class="swiper-slide">snow</div>
<div class="swiper-slide">Slide 1</div>
<div class="swiper-slide">Slide 2</div>
<div class="swiper-slide">Slide 3</div>
<div class="swiper-slide">Slide 4</div>
<div class="swiper-slide">Slide 5</div>
<div class="swiper-slide">Slide 6</div>
<div class="swiper-slide">Slide 7</div>
<div class="swiper-slide">Slide 8</div>
<div class="swiper-slide">Slide 9</div>
<div class="swiper-slide">Slide 10</div>
</div>
<div class="swiper-button-prev"></div>
<div class="swiper-button-next"></div>
</div>
</div>
</template>
<script setup lang="ts">
onMounted(() => {
let swiper = new Swiper(".mySwiper", {
slidesPerView: 5, // 轮播区域展示的数量
spaceBetween: 30,
mousewheel: true,
keyboard: true,
loop: true, // 循环播放
speed: 2500,
autoplay: { // 自动播放
delay: 2500,
disableOnInteraction: false,
},
navigation: {
prevEl: ".swiper-button-prev",
nextEl: ".swiper-button-next",
},
// pagination: {
// el: ".swiper-pagination",
// clickable: true,
// }
});
})
</script>
<style scoped lang="scss">
.container{
.swiper {
width: 500px;
height: 100px;
border: 2px solid #ff0000;
}
.swiper-slide {
text-align: center;
font-size: 18px;
background: #fff;
background: #ccc;
display: -webkit-box;
display: -ms-flexbox;
display: -webkit-flex;
display: flex;
-webkit-box-pack: center;
-ms-flex-pack: center;
-webkit-justify-content: center;
justify-content: center;
-webkit-box-align: center;
-ms-flex-align: center;
-webkit-align-items: center;
align-items: center;
}
.swiper-button-prev{
background: #eee;
width: 30px;
height: 30px;
border-radius: 50%;
}
.swiper-button-next{
background: #eee;
width: 30px;
height: 30px;
border-radius: 50%;
}
.swiper-slide img {
display: block;
width: 100%;
height: 100%;
object-fit: cover;
}
// 去掉左右箭头默认样式
.swiper-button-prev:after{
display: none;
}
.swiper-button-next:after{
display: none;
}
// 定义新的样式
.swiper-button-prev{
width: 35px;
height: 35px;
background: url('~/assets/imgs/nginx.jpg') no-repeat;
bottom: 15px;
}
.swiper-button-next{
width: 35px;
height: 35px;
background:url('~/assets/imgs/nginx.jpg') no-repeat;
bottom: 15px;
}
}
</style>
3.3、效果展示
四、过程记录
记录一、
再引入swiper时,尝试了npm 包: swiper、vue-awesome-swiper等,尝试在nuxt3里增加plugin的方式引入,都没有成功,个人感觉应该是可以的,可能是我没有尝试对,最后使用了在nuxt.config.ts中引入的方法。
记录二、
在nuxt.config.ts中引入网络上的js、css,可能会加载慢导致页面加载速度也慢,我们可以把js、css放在public目录下,引入本地文件,这样可以加快文件请求速度。
五、欢迎交流指正,关注我,一起学习。