基于uni-app内置组件(swiper)和扩展UI组件(uni-ui)实现一版自定义样式轮播图组件
template模块
<template>
<uni-swiper-dot
:info="props.swiperList"
:current="currentIndex"
:field="props.filed"
:mode="props.mode"
:dotsStyles="dotsStyles"
@clickItem="(e) => getCurrentIndex(e, 'click')"
>
<swiper
class="swiper"
:current="currentIndex"
:autoplay="props.autoplay"
:interval="props.interval"
:duration="props.duration"
@change="(e) => getCurrentIndex(e, 'change')"
>
<swiper-item v-for="(item, index) in props.swiperList" :key="index">
<view class="swiper-item" @tap="goDetail(item)">
<image class="img" :src="item[props.filed]" mode="scaleToFill"/>
</view>
</swiper-item>
</swiper>
</uni-swiper-dot>
</template>
js模块
<script setup>
import { reactive, ref } from 'vue'
/**
* 参数名 类型 描述
* swiperList Array swiper列表数据
* isClick Boolean 是否可以点击轮播图
* filed String 接口中存储轮播图的字段
* mode String 指示点类型 可选:default 、round 、nav 、 indexes
* autoplay Boolean 是否自动切换
* interval Number 轮播图自动切换间隔时间
* duration Number 滑动动画时长
*/
const props = defineProps({
swiperList: {
type: Array,
default: () => []
},
isClick: {
type: Boolean,
default: () => true
},
filed: {
type: String,
default: () => ''
},
mode: {
type: String,
default: () => 'round'
},
autoplay: {
type: Boolean,
default: () => true
},
interval: {
type: Number,
default: () => 5000
},
duration: {
type: Number,
default: () => 500
}
})
const currentIndex = ref(0)
const dotsStyles = reactive({
border: 'none',
backgroundColor: '#2a77ff',
selectedBackgroundColor: '#2a77ff',
selectedBorder: 'none',
})
//点击轮播图指示点展示对应图片
const getCurrentIndex = (e, type) => {
currentIndex.value = type === 'click' ? e : e.detail.current;
}
//点击轮播图跳转页面
const goDetail = (item) => {
if (props.isClick) {
uni.navigateTo({
url: `/pages/detail/index?params=${encodeURIComponent(JSON.stringify(item))}`
})
}
}
</script>
style模块
<style lang="scss">
.swiper {
width: 100%;
height: 350rpx;
background-color: #fff;
padding-left: 2%;
.swiper-item {
width: 96%;
height: 100%;
.img {
width: 100%;
height: 100%;
border-radius: 20rpx;
}
}
}
</style>
父组件使用
<template>
<my-swiper :swiper-list="swiperList" filed="imgSrc"/>
</template>
<script setup>
import { reactive } from 'vue'
import mySwiper from '轮播图组件存放位置'
//数组根据个人需求可定义多个参数
const swiperList = reactive([
{
imgSrc: ''
},
{
imgSrc: ''
},
{
imgSrc: ''
}
])
</script>
详情页组件(前提:轮播图配成可点击)
<template>
<view class="detail">
<image :src="params.imgSrc" class="img"/>
</view>
</template>
<script setup>
import { ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
const params = ref('')
onLoad((options) => {
params.value = JSON.parse(decodeURIComponent(options.params))
})
</script>