话不多说直接上代码
安装依赖:
npm install swiper
组件代码:
<template>
<div class="swiper-box">
<div class="swiper-container">
<div class="swiper-wrapper">
<slot name="img"></slot>
</div>
<div class="swiper-pagination"></div>
</div>
</div>
</template>
<script>
import Swiper from "swiper/swiper-bundle.min.js";
import "swiper/swiper-bundle.min.css";
// 当前版本"swiper": "^6.4.8"
// template部分
// <Banner :key="list.length" :clickBanner="clickBanner"> // 1、v-bind:key="list.length"防止渲染后loop失效
// <img slot="img" v-for="(item, index) in list" :key="index" class="swiper-slide" :src="item.src" :alt="item.name">
// </Banner>
// script部分代码
// import Banner from './components/banner'
// components: {
// Banner
// },
// created() {
// getBanners().then(res => {
// this.list = res.data.list // [{src: './assets/img/banner01.jpg', id: '001', name: '图1'}]
// })
// }
export default {
props: {
clickBanner: Function, // 点击获取当前索引
options: {
type: Object,
default: () => {
return {
loop: true,
observer:true,//修改swiper自己或子元素时,自动初始化swiper
observeParents:true,//修改swiper的父元素时,自动初始化swiper
pagination: {
el: ".swiper-pagination"
}
}
}
}
},
data() {
return {}
},
mounted() {
const VM = this
const myOption = {
...this.options,
on: {
click: function () {
// 这里有坑,需要注意的是:this 指向的是 swpier 实例,而不是当前的 vue, 因此借助 vm,来调用 methods 里的方法
// console.log(this); // this === Swiper
// 当前活动块的索引,与activeIndex不同的是,在loop模式下不会将 复制的块 的数量计算在内。
VM.clickBanner(this.realIndex);
}
}
}
new Swiper(".swiper-container", myOption)
}
};
</script>
<style scoped>
.swiper-box{
width: 100%;
}
.box >>> .swiper-container{
width: 100%;
}
</style>
如何使用该组件:
<template>
<div id="app">
<Banner :key="list.length" :clickBanner="clickBanner">
<img slot="img" v-for="(item, index) in list" :key="index" class="swiper-slide" :src="item.src" :alt="item.name">
</Banner>
</div>
</template>
<script>
import Banner from './components/banner'
export default {
name: 'App',
components: {
Banner
},
data () {
return {
list: []
}
},
created() {
setTimeout(() => { // 模拟api请求
this.list = [
{src: require('./assets/img/banner01.jpg'), id: '001', name: '图1'},
{src: require('./assets/img/banner02.jpg'), id: '002', name: '图2'},
{src: require('./assets/img/banner03.jpg'), id: '003', name: '图3'}
]
}, 500)
},
methods: {
clickBanner(index) {
console.log(this.list[index])
}
}
}
</script>
<style scoped>
html,body,#app{
width: 100%;
height: 100%;
}
.swiper-slide{
display: block;
width: 100%;
height: 200px;
}
</style>