如何在vue项目中使用Swiper
首先安装Swiper插件
yarn add swiper@5.2.0
cnpm install swiper@5.2.0 -save
然后在src下面的main.js中引入
import 'swiper/css/swiper.min.css'
新建vue组件 SwiperCom.vue 写入一下代码
<template>
<div class="swiper-container" :class="name">
<div class="swiper-wrapper">
<slot></slot>
</div>
// 分页按钮
// <div class="swiper-pagination"></div>
</div>
</template>
<script>
export default {
props: {
name: {
type: String,
default: ''
}
}
}
</script>
<style>
</style>
在需要使用轮播图的组件内引入swiper和组件SwiperCom并注册
import Swiper from 'swiper'
import SwiperCom from '../components/SwiperCom'
<script>
export default {
components: { SwiperCom }
}
</script>
在template需要的位置使用SwiperCom
name在swiper实例化时使用,同一个页面有多个轮播图,name不能相同
<template>
<SwiperCom name="login-banner">
<div v-for="banner in imgList" :key="banner.id" class="swiper-slide">
<img :src="banner.imgUrl" alt="">
</div>
</SwiperCom>
</template>
如果是静态的图片数据 在data中写imgList
<script>
export default {
components: { SwiperCom }
data() {
return {
imgList: [
{ id: 0, imgUrl: require('@/assets/login/bg1.jpg') },
{ id: 1, imgUrl: require('@/assets/login/bg2.jpg') },
{ id: 2, imgUrl: require('@/assets/login/bg3.jpg') }
]
}
}
}
</script>
Swiper实例化 实例化时添加相关的属性配置
<script>
export default {
created() {
this.$nextTick(() => {
new Swiper('.login-banner', {
loop: true, // 循环轮播
effect: 'fade', // 淡入淡出效果 默认左右轮播
autoplay: true // 自动轮播
pagination: { // 分页按钮
el: '.swiper-pagination'
}
})
})
}
}
</script>
如果时动态获取的图片 我们只需要在获取打图片后将imgList赋值,在拿到数据后实例化即可
instance.request({...... }).then(res => {
if (res.data.data) { this.imgList= [...res.data.data] }
/* eslint-disable no-new */
this.$nextTick(() => {
new Swiper(".films-banner", {
loop: true,
autoplay: true,
pagination: {
el: '.swiper-pagination'
}
})
})
})
如果需要其他样式的轮播图 访问下面的网址
https://3.swiper.com.cn/demo/index.html
挑选 >> 在新窗口打开 >> 右键查看源代码 >> 查看script标签属性即可
如果需要更多Swiper的API 访问下面的网址
https://www.swiper.com.cn/api/pagination/280.html