uniapp vue3封装 swiper 组件

99 阅读1分钟
一、在 components 中新建 swiperCom 文件夹并新建 swiperCom.vue文件
1、写入 html 代码
<template>
    <swiper class="swiperBox" indicator-dots autoplay :interval="swiperTime" circular previous-margin="65rpx"
        next-margin="65rpx" @change="swiperChange">
        <swiper-item v-for="(item,index) in swiperData" :key="item.id" @click="swiperClick(item)">
            <view :class="index == acitveInd ? 'swiperActive' : ''" class="swiper-item">{{item.title}}</view>
        </swiper-item>
    </swiper>
</template>
2、写入 css 代码
.swiperBox {
    width: 750rpx;
    height: 300rpx;
    margin: 20rpx 0;
    box-sizing: border-box;
    
    swiper-item {
        display: flex;
        align-items: center;
        justify-content: center;
​
        .swiper-item {
            width: 100%;
            margin-top: 0;
            text-align: center;
            line-height: 280rpx;
            background: rgba(0, 0, 0, .3);
            border-radius: 20rpx;
            overflow: hidden;
        }
​
        .swiperActive {
            height: 300rpx !important;
            margin: 0rpx 10rpx;
        }
    }
}
3、写入 js 代码
import {
    reactive,
    ref,
    defineProps,
    defineEmits,
} from 'vue';
// 父级传过来的值
const { swiperData,swiperTime } = defineProps({
    swiperData: {
        type: null,
        require: true
    },
    swiperTime: {
        type: Number,
        require: true
    },
})
​
// 当前显示的元素
let acitveInd = ref(0);
​
// 注册父级事件
const emit = defineEmits(['swiperChange','swiperClick']);
// 切换改变
const swiperChange = (event) => {
    acitveInd.value = event.detail.current;
    // 触发父级事件
    emit('swiperChange',acitveInd.value);
};
// 点击
const swiperClick = (item) => {
    // 触发父级事件
    emit('swiperClick',item);
};
二、父组件调用
1、html 代码
<swiperCom :swiperData="swiperData" :swiperTime="swiperTime" @swiperChange="swiperChange" @swiperClick="swiperClick"></swiperCom>
2、js 代码
<script setup>
    import { reactive, ref } from 'vue';
​
        // 引入组件
    import swiperCom from '@/components/swiperCom/swiperCom.vue';
​
    // 自动轮播时间
    const swiperTime = ref(2000);
    // 轮播数据
    const swiperData = reactive([
        {
            id: 1,
            title: '标题1',
        },
        {
            id: 2,
            title: '标题2',
        },
        {
            id: 3,
            title: '标题3',
        },
    ]);
​
    // 轮播时执行 --- 每次轮播都会执行
    const swiperChange = (val) => {
        console.log(val,'val');
    }
    // 点击某个执行 --- 可执行跳转等操作
    const swiperClick = (val) => {
        console.log(val,'clickVal');
    }
</script>
三、修改指示点样式需要在 App.vue 中写如下代码
/* uni-app中的条件判断语句 */
/* #ifdef H5 */
uni-swiper .uni-swiper-dot {
    width: 10rpx;
    height: 10rpx;
}
​
uni-swiper .uni-swiper-dot-active {
    width: 30rpx;
    border-radius: 10rpx;
}
/* #endif *//* #ifdef MP-WEIXIN */
wx-swiper .wx-swiper-dot {
    width: 10rpx;
    height: 10rpx;
}
​
wx-swiper .wx-swiper-dot-active {
    width: 30rpx;
    height: 10rpx;
    border-radius: 10rpx;
}
/* #endif */