uniapp vue3封装 swiper 组件

一、在 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 */
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值