一、引入包
首先需要下载包
npm i swiper@5 --save
二、使用步骤
1.引入库
在我们的入口文件main.js下引入样式
// 引入swiper的样式
import 'swiper/css/swiper.css'
2.使用
在需要做轮播的地方引入swiper
import Swiper from 'swiper'
swiper的基本内容:
<div class="swiper-container">
<div class="swiper-wrapper">
<div class="swiper-slide">Slide 1</div>
<div class="swiper-slide">Slide 2</div>
<div class="swiper-slide">Slide 3</div>
</div>
<!-- 如果需要分页器 -->
<div class="swiper-pagination"></div>
<!-- 如果需要导航按钮 -->
<div class="swiper-button-prev"></div>
<div class="swiper-button-next"></div>
<!-- 如果需要滚动条 -->
<div class="swiper-scrollbar"></div>
</div>
在App.vue简单的使用:
<template>
<div id="app">
<div class="swiper-container">
<div class="swiper-wrapper">
<div class="swiper-slide" v-for="(i, index) in img" :key="index">
<img class="images" :src="i.imgUrl" />
</div>
</div>
<!-- 如果需要分页器 -->
<div class="swiper-pagination"></div>
<!-- 如果需要导航按钮 -->
<div class="swiper-button-prev"></div>
<div class="swiper-button-next"></div>
<!-- 如果需要滚动条 -->
<div class="swiper-scrollbar"></div>
</div>
</div>
</template>
首先我们需要准备一个img的数组,里面包含了图片的地址,这里可以去网上复制图像的地址组成字符串即可
我们需要解决页面还没有渲染swiper的实例还未完成,导致轮播图动不了,我们需要使用watch监听加上nextTick
来解决该问题
watch: {
img: {
handler() {
this.$nextTick(() => {
var mySwiper = new Swiper('.swiper-container', {
loop: true,
// 如果需要分页器
pagination: {
el: '.swiper-pagination',
clickable: true
},
// 如果需要前进后退按钮
navigation: {
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev'
}
})
console.log(mySwiper)
})
}
}
}
注意这里的img是mock的,起始是空数据,关于mock可以参考我的另一篇文章:https://blog.csdn.net/The_more_more/article/details/124237127
里面的配置参数参考swiper的官网:https://3.swiper.com.cn/
App.vue的完整代码:
<template>
<div id="app">
<div class="swiper-container">
<div class="swiper-wrapper">
<div class="swiper-slide" v-for="(i, index) in img" :key="index">
<img class="images" :src="i.imgUrl" />
</div>
</div>
<!-- 如果需要分页器 -->
<div class="swiper-pagination"></div>
<!-- 如果需要导航按钮 -->
<div class="swiper-button-prev"></div>
<div class="swiper-button-next"></div>
<!-- 如果需要滚动条 -->
<div class="swiper-scrollbar"></div>
</div>
</div>
</template>
<script>
import Swiper from 'swiper'
export default {
name: 'App',
data() {
return {
img: [] // 因为这是mock过来的,所以这里是空数组
}
},
watch: {
img: {
handler() {
this.$nextTick(() => {
var mySwiper = new Swiper('.swiper-container', {
loop: true,
// 如果需要分页器
pagination: {
el: '.swiper-pagination',
clickable: true
},
// 如果需要前进后退按钮
navigation: {
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev'
}
})
console.log(mySwiper)
})
}
}
}
}
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
.images {
width: 100%;
}
.swiper-container {
width: 600px;
height: 300px;
}
</style>