利用Taro的Swipe封装的轮播组件
2022-11-07 本文已影响0人
T_guo
背景描述
由于我们目前几个小程序,广告轮播用到比较频繁,为了方便在taro的Swipe组件上进行了二次封装。该轮播组件是taro+vue3写的,写的有不足的大方各位大佬勿喷,欢迎各路大神指正。
直接上代码
<template>
<view class="swiper-banners">
<swiper
class="swiper-banners-layout"
:autoplay="data.autoplay"
circular="true"
@change="swiperChange"
v-show="bannersList.length > 0 ? true : false"
>
<swiper-item v-for="(item, index) in bannersList" :key="index" @tap="clickBannerItem(index, item)">
<image class="swiper-banners-layout-item-img" :src="item.url" mode="aspectFill"></image>
</swiper-item>
</swiper>
<!--重置小圆点的样式 -->
<view class="swiper-banners-dots" v-show="bannersList.length > 1 ? true : false">
<view
v-for="(item, index) in bannersList"
:key="index"
:class="data.currentSwiper == index ? 'swiper-banners-active' : 'swiper-banners-dot'"
></view>
</view>
</view>
</template>
<script setup>
import { watch } from 'vue';
import { reactive } from 'vue';
const props = defineProps({
bannersList: {
type: Array,
default: () => [],
},
});
const emit = defineEmits(['clickBannerItem']);
let data = reactive({
autoplay: false,
compress: '?x-oss-process=image/resize,w_720',
currentSwiper: 0,
});
watch(
() => props.bannersList,
newVal => {
if (newVal) {
data.autoplay = true;
}
},
);
const swiperChange = res => {
// 监听
data.currentSwiper = res.detail.current;
};
const clickBannerItem = (index, item) => {
emit('clickBannerItem', index, item);
};
</script>
<style lang="scss">
.swiper-banners {
position: relative;
margin: 0 16px;
border-radius: 8px;
overflow: hidden;
.swiper-banners-layout {
width: 343px;
height: 80px;
border-radius: 8px;
overflow: hidden;
//适配ios
transform: translateY(0);
.swiper-banners-layout-item-img {
width: 343px;
height: 80px;
border-radius: 8px;
}
}
.swiper-banners-dots {
position: absolute;
top: 69px;
left: 50%;
transform: translateX(-50%);
display: flex;
align-items: center;
.swiper-banners-dot {
width: 4px;
height: 4px;
background: #ffffff;
opacity: 0.2;
border-radius: 5px;
margin-right: 4px;
}
.swiper-banners-active {
width: 12px;
height: 4px;
background: #ffffff;
opacity: 0.8;
border-radius: 5px;
margin-right: 4px;
}
}
}
</style>
如何使用
- 首页引入组件
/*具体路径可以根据自己的情况去写*/
import Banners from '../xx/xx/Banners';
import { reactive} from 'vue';
/*定义数据*/
const data = reactive({
banners: [{ url: "xxxxxx" }],
});
- 在使用的地方写如下
/*具体路径可以根据自己的情况去写*/
<Banners
class="banner-content"
:bannersList="banners"
@clickBannerItem="clickBannerItem()"
></Banners>
- banner事件
//banner点击
const clickBannerItem = (index, item) => {
console.log(index, item);
};