cl-banner.uvue 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. <template>
  2. <view
  3. class="cl-banner"
  4. :class="[pt.className]"
  5. :style="{
  6. height: parseRpx(height)
  7. }"
  8. @touchstart="onTouchStart"
  9. @touchmove="onTouchMove"
  10. @touchend="onTouchEnd"
  11. @touchcancel="onTouchEnd"
  12. >
  13. <view
  14. class="cl-banner__list"
  15. :class="{
  16. 'is-transition': isAnimating
  17. }"
  18. :style="{
  19. transform: `translateX(${slideOffset}px)`
  20. }"
  21. >
  22. <view
  23. class="cl-banner__item"
  24. v-for="(item, index) in list"
  25. :key="index"
  26. :class="[
  27. pt.item?.className,
  28. `${item.isActive ? `${pt.itemActive?.className}` : ''}`
  29. ]"
  30. :style="{
  31. width: `${getSlideWidth(index)}px`
  32. }"
  33. @tap="handleSlideClick(index)"
  34. >
  35. <slot :item="item" :index="index">
  36. <image
  37. :src="item.url"
  38. mode="aspectFill"
  39. class="cl-banner__item-image"
  40. :class="[pt.image?.className]"
  41. ></image>
  42. </slot>
  43. </view>
  44. </view>
  45. <view class="cl-banner__dots" :class="[pt.dots?.className]" v-if="showDots">
  46. <view
  47. class="cl-banner__dots-item"
  48. v-for="(item, index) in list"
  49. :key="index"
  50. :class="[
  51. {
  52. 'is-active': item.isActive
  53. },
  54. pt.dot?.className,
  55. `${item.isActive ? `${pt.dotActive?.className}` : ''}`
  56. ]"
  57. ></view>
  58. </view>
  59. </view>
  60. </template>
  61. <script setup lang="ts">
  62. import { computed, ref, onMounted, watch, getCurrentInstance, type PropType } from "vue";
  63. import { parsePt, parseRpx } from "@/cool";
  64. import type { PassThroughProps } from "../../types";
  65. type Item = {
  66. url: string;
  67. isActive: boolean;
  68. };
  69. defineOptions({
  70. name: "cl-banner"
  71. });
  72. defineSlots<{
  73. item(props: { item: Item; index: number }): any;
  74. }>();
  75. const props = defineProps({
  76. // 透传属性
  77. pt: {
  78. type: Object,
  79. default: () => ({})
  80. },
  81. // 轮播项列表
  82. list: {
  83. type: Array as PropType<string[]>,
  84. default: () => []
  85. },
  86. // 上一个轮播项的左边距
  87. previousMargin: {
  88. type: Number,
  89. default: 0
  90. },
  91. // 下一个轮播项的右边距
  92. nextMargin: {
  93. type: Number,
  94. default: 0
  95. },
  96. // 是否自动轮播
  97. autoplay: {
  98. type: Boolean,
  99. default: true
  100. },
  101. // 自动轮播间隔时间(ms)
  102. interval: {
  103. type: Number,
  104. default: 5000
  105. },
  106. // 是否显示指示器
  107. showDots: {
  108. type: Boolean,
  109. default: true
  110. },
  111. // 是否禁用触摸
  112. disableTouch: {
  113. type: Boolean,
  114. default: false
  115. },
  116. // 高度
  117. height: {
  118. type: [Number, String],
  119. default: 300
  120. }
  121. });
  122. const emit = defineEmits(["change", "item-tap"]);
  123. const { proxy } = getCurrentInstance()!;
  124. // 透传属性类型定义
  125. type PassThrough = {
  126. className?: string;
  127. item?: PassThroughProps;
  128. itemActive?: PassThroughProps;
  129. image?: PassThroughProps;
  130. dots?: PassThroughProps;
  131. dot?: PassThroughProps;
  132. dotActive?: PassThroughProps;
  133. };
  134. const pt = computed(() => parsePt<PassThrough>(props.pt));
  135. /** 当前激活的轮播项索引 */
  136. const activeIndex = ref(0);
  137. /** 轮播项列表 */
  138. const list = computed<Item[]>(() => {
  139. return props.list.map((e, i) => {
  140. return {
  141. url: e,
  142. isActive: i == activeIndex.value
  143. } as Item;
  144. });
  145. });
  146. /** 轮播容器的水平偏移量(px) */
  147. const slideOffset = ref(0);
  148. /** 是否正在执行动画过渡 */
  149. const isAnimating = ref(false);
  150. /** 轮播容器的总宽度(px) */
  151. const bannerWidth = ref(0);
  152. /** 单个轮播项的宽度(px) - 用于缓存计算结果 */
  153. const slideWidth = ref(0);
  154. /** 触摸开始时的X坐标 */
  155. const touchStartPoint = ref(0);
  156. /** 触摸开始时的时间戳 */
  157. const touchStartTimestamp = ref(0);
  158. /** 触摸开始时的初始偏移量 */
  159. const initialOffset = ref(0);
  160. /**
  161. * 更新轮播容器的位置
  162. * 根据当前激活索引计算并设置容器的偏移量
  163. */
  164. function updateSlidePosition() {
  165. if (bannerWidth.value == 0) return;
  166. // 计算累积偏移量,考虑每个位置的动态边距
  167. let totalOffset = 0;
  168. // 遍历当前索引之前的所有项,累加它们的宽度
  169. for (let i = 0; i < activeIndex.value; i++) {
  170. const itemPreviousMargin = i == 0 ? 0 : props.previousMargin;
  171. const itemNextMargin = i == props.list.length - 1 ? 0 : props.nextMargin;
  172. const itemWidthAtIndex = bannerWidth.value - itemPreviousMargin - itemNextMargin;
  173. totalOffset += itemWidthAtIndex;
  174. }
  175. // 当前项的左边距
  176. const currentPreviousMargin = activeIndex.value == 0 ? 0 : props.previousMargin;
  177. // 设置最终的偏移量:负方向移动累积宽度,然后加上当前项的左边距
  178. slideOffset.value = -totalOffset + currentPreviousMargin;
  179. }
  180. /**
  181. * 获取指定索引轮播项的宽度
  182. * @param index 轮播项索引
  183. * @returns 轮播项宽度(px)
  184. */
  185. function getSlideWidth(index: number): number {
  186. // 动态计算每个项的宽度,考虑边距
  187. const itemPreviousMargin = index == 0 ? 0 : props.previousMargin;
  188. const itemNextMargin = index == props.list.length - 1 ? 0 : props.nextMargin;
  189. return bannerWidth.value - itemPreviousMargin - itemNextMargin;
  190. }
  191. /**
  192. * 计算并缓存轮播项宽度
  193. * 使用固定的基础宽度计算,避免动态变化导致的性能问题
  194. */
  195. function calculateSlideWidth() {
  196. const baseWidth = bannerWidth.value - props.previousMargin - props.nextMargin;
  197. slideWidth.value = baseWidth;
  198. }
  199. /**
  200. * 测量轮播容器的尺寸信息
  201. * 获取容器宽度并初始化相关计算
  202. */
  203. function getRect() {
  204. uni.createSelectorQuery()
  205. .in(proxy)
  206. .select(".cl-banner")
  207. .boundingClientRect((node) => {
  208. bannerWidth.value = (node as NodeInfo).width ?? 0;
  209. // 重新计算宽度和位置
  210. calculateSlideWidth();
  211. updateSlidePosition();
  212. })
  213. .exec();
  214. }
  215. /** 自动轮播定时器 */
  216. let autoplayTimer: number = 0;
  217. /**
  218. * 清除自动轮播定时器
  219. */
  220. function clearAutoplay() {
  221. if (autoplayTimer != 0) {
  222. clearInterval(autoplayTimer);
  223. autoplayTimer = 0;
  224. }
  225. }
  226. /**
  227. * 启动自动轮播
  228. */
  229. function startAutoplay() {
  230. if (props.list.length <= 1) return;
  231. if (props.autoplay) {
  232. clearAutoplay();
  233. }
  234. isAnimating.value = true;
  235. // @ts-ignore
  236. autoplayTimer = setInterval(() => {
  237. if (activeIndex.value >= props.list.length - 1) {
  238. activeIndex.value = 0;
  239. } else {
  240. activeIndex.value++;
  241. }
  242. }, props.interval);
  243. }
  244. /**
  245. * 处理触摸开始事件
  246. * 记录触摸起始状态,准备手势识别
  247. * @param e 触摸事件对象
  248. */
  249. function onTouchStart(e: UniTouchEvent) {
  250. // 如果禁用触摸,则不进行任何操作
  251. if (props.disableTouch) return;
  252. // 单项或空列表不支持滑动
  253. if (props.list.length <= 1) return;
  254. // 清除自动轮播
  255. clearAutoplay();
  256. // 禁用动画,开始手势跟踪
  257. isAnimating.value = false;
  258. touchStartPoint.value = e.touches[0].clientX;
  259. touchStartTimestamp.value = Date.now();
  260. initialOffset.value = slideOffset.value;
  261. }
  262. /**
  263. * 处理触摸移动事件
  264. * 实时更新容器位置,实现跟手效果
  265. * @param e 触摸事件对象
  266. */
  267. function onTouchMove(e: UniTouchEvent) {
  268. if (props.list.length <= 1 || props.disableTouch) return;
  269. // 计算手指移动距离,实时更新偏移量
  270. const deltaX = e.touches[0].clientX - touchStartPoint.value;
  271. slideOffset.value = initialOffset.value + deltaX;
  272. }
  273. /**
  274. * 处理触摸结束事件
  275. * 根据滑动距离和速度判断是否切换轮播项
  276. */
  277. function onTouchEnd() {
  278. if (props.list.length <= 1) return;
  279. // 恢复动画效果
  280. isAnimating.value = true;
  281. // 计算滑动距离、时间和速度
  282. const deltaX = slideOffset.value - initialOffset.value;
  283. const deltaTime = Date.now() - touchStartTimestamp.value;
  284. const velocity = Math.abs(deltaX) / deltaTime; // px/ms
  285. let newIndex = activeIndex.value;
  286. // 使用当前项的实际宽度进行滑动判断
  287. const currentSlideWidth = getSlideWidth(activeIndex.value);
  288. // 判断是否需要切换:滑动距离超过30%或速度够快
  289. if (Math.abs(deltaX) > currentSlideWidth * 0.3 || velocity > 0.3) {
  290. // 向右滑动且不是第一项 -> 上一项
  291. if (deltaX > 0 && activeIndex.value > 0) {
  292. newIndex = activeIndex.value - 1;
  293. }
  294. // 向左滑动且不是最后一项 -> 下一项
  295. else if (deltaX < 0 && activeIndex.value < props.list.length - 1) {
  296. newIndex = activeIndex.value + 1;
  297. }
  298. }
  299. // 更新索引
  300. activeIndex.value = newIndex;
  301. updateSlidePosition();
  302. // 恢复自动轮播
  303. setTimeout(() => {
  304. startAutoplay();
  305. }, 300);
  306. }
  307. /**
  308. * 处理轮播项点击事件
  309. * @param index 被点击的轮播项索引
  310. */
  311. function handleSlideClick(index: number) {
  312. emit("item-tap", index);
  313. }
  314. /** 监听激活索引变化 */
  315. watch(activeIndex, (val: number) => {
  316. updateSlidePosition();
  317. emit("change", val);
  318. });
  319. onMounted(() => {
  320. getRect();
  321. startAutoplay();
  322. });
  323. </script>
  324. <style lang="scss" scoped>
  325. .cl-banner {
  326. @apply relative z-10 rounded-xl;
  327. &__list {
  328. @apply flex flex-row h-full w-full overflow-visible;
  329. &.is-transition {
  330. transition-property: transform;
  331. transition-duration: 0.3s;
  332. }
  333. }
  334. &__item {
  335. @apply relative duration-200;
  336. transition-property: transform;
  337. &-image {
  338. @apply w-full h-full rounded-xl;
  339. }
  340. }
  341. &__dots {
  342. @apply flex flex-row items-center justify-center;
  343. @apply absolute bottom-3 left-0 w-full;
  344. &-item {
  345. @apply w-2 h-2 rounded-full mx-1;
  346. background-color: rgba(255, 255, 255, 0.3);
  347. transition-property: width, background-color;
  348. transition-duration: 0.3s;
  349. &.is-active {
  350. @apply bg-white w-5;
  351. }
  352. }
  353. }
  354. }
  355. </style>