vue2使用swiper的时候需要安装swiper5和vue-awesome-swiper4最新版的swiper是比较适合vue3
swiper的配置手册和swiper最新官网上的也不一样,需要按照旧的手册配置options
注意:前进后退按钮需要自定元素,放到swiper外面,否则会出现跟着图片走的情况
<template>
<div class="image-card">
<swiper ref="swiper" :options="swiperOption" @slideChange="slideChange">
<swiper-slide
v-for="(item, index) in schema"
:key="item.id"
class="image-card_item"
@click.native="handleClick(index)"
>
<news-image :id="item['attachment_id']" />
<div
:class="[
'image-card_item__text',
{ 'image-card_item__active': activeIndex === index },
]"
>
<span>{{ item.content }}</span>
</div>
</swiper-slide>
</swiper>
<div class="swiper-button-prev" @click="handlerPrev" />
<div class="swiper-button-next" @click="handlerNext" />
</div>
</template>
<script>
import newsImage from './news-image.vue';
import 'swiper/css/swiper.css';
import { Swiper, SwiperSlide } from 'vue-awesome-swiper';
export default {
components: {
newsImage,
SwiperSlide,
Swiper,
},
props: {
schema: {
type: Array,
required: true,
},
},
data() {
return {
swiperOption: {
slidesPerView: 3,
spaceBetween: 20,
slideToClickedSlide: true,
autoplay: {
delay: 30000,
loop: true,
disableOnInteraction: false,
},
//前进后退按钮
navigation: {
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev',
},
},
activeIndex: 0,
};
},
methods: {
slideChange() {
var realIndex = this.$refs.swiper.$swiper.realIndex;
this.activeIndex = realIndex;
this.$emit('click', this.schema[realIndex]);
},
handlerPrev() {
this.$refs.swiper.$swiper.slidePrev();
},
handlerNext() {
this.$refs.swiper.$swiper.slideNext();
},
handleClick(index) {
this.activeIndex = index;
this.$emit('click', this.schema[index]);
},
},
};
</script>
<style lang="scss" scoped>
.image-card {
width: 800px;
position: relative;
&_item {
height: 200px;
border-radius: 10px;
overflow: hidden;
position: relative;
cursor: pointer;
.q-image {
width: 100%;
height: 100%;
}
&__text {
width: 100%;
padding: 9px 21px;
position: absolute;
bottom: 0;
background: #000;
opacity: 0.4;
height: 70px;
box-sizing: border-box;
span {
font-family: SourceHanSansCN-Medium;
font-size: 18px;
color: #fff;
font-weight: 500;
line-height: 26px;
overflow: hidden;
text-overflow: ellipsis;
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 2;
}
}
&__active {
opacity: 0.8;
background: #3d7fff;
}
}
}
</style>