cl-banner.uvue 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  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. const isTouching = ref(false);
  162. /** 位置更新防抖定时器 */
  163. let positionUpdateTimer: number = 0;
  164. /**
  165. * 更新轮播容器的位置
  166. * 根据当前激活索引计算并设置容器的偏移量
  167. */
  168. function updateSlidePosition() {
  169. if (bannerWidth.value == 0) return;
  170. // 防抖处理,避免频繁更新
  171. if (positionUpdateTimer != 0) {
  172. clearTimeout(positionUpdateTimer);
  173. }
  174. // @ts-ignore
  175. positionUpdateTimer = setTimeout(() => {
  176. // 计算累积偏移量,考虑每个位置的动态边距
  177. let totalOffset = 0;
  178. // 遍历当前索引之前的所有项,累加它们的宽度
  179. for (let i = 0; i < activeIndex.value; i++) {
  180. const itemPreviousMargin = i == 0 ? 0 : props.previousMargin;
  181. const itemNextMargin = i == props.list.length - 1 ? 0 : props.nextMargin;
  182. const itemWidthAtIndex = bannerWidth.value - itemPreviousMargin - itemNextMargin;
  183. totalOffset += itemWidthAtIndex;
  184. }
  185. // 当前项的左边距
  186. const currentPreviousMargin = activeIndex.value == 0 ? 0 : props.previousMargin;
  187. // 设置最终的偏移量:负方向移动累积宽度,然后加上当前项的左边距
  188. slideOffset.value = -totalOffset + currentPreviousMargin;
  189. positionUpdateTimer = 0;
  190. }, 10);
  191. }
  192. /**
  193. * 获取指定索引轮播项的宽度
  194. * @param index 轮播项索引
  195. * @returns 轮播项宽度(px)
  196. */
  197. function getSlideWidth(index: number): number {
  198. // 动态计算每个项的宽度,考虑边距
  199. const itemPreviousMargin = index == 0 ? 0 : props.previousMargin;
  200. const itemNextMargin = index == props.list.length - 1 ? 0 : props.nextMargin;
  201. return bannerWidth.value - itemPreviousMargin - itemNextMargin;
  202. }
  203. /**
  204. * 计算并缓存轮播项宽度
  205. * 使用固定的基础宽度计算,避免动态变化导致的性能问题
  206. */
  207. function calculateSlideWidth() {
  208. const baseWidth = bannerWidth.value - props.previousMargin - props.nextMargin;
  209. slideWidth.value = baseWidth;
  210. }
  211. /**
  212. * 测量轮播容器的尺寸信息
  213. * 获取容器宽度并初始化相关计算
  214. */
  215. function getRect() {
  216. uni.createSelectorQuery()
  217. .in(proxy)
  218. .select(".cl-banner")
  219. .boundingClientRect((node) => {
  220. bannerWidth.value = (node as NodeInfo).width ?? 0;
  221. // 重新计算宽度和位置
  222. calculateSlideWidth();
  223. updateSlidePosition();
  224. })
  225. .exec();
  226. }
  227. /** 自动轮播定时器 */
  228. let autoplayTimer: number = 0;
  229. /**
  230. * 清除自动轮播定时器
  231. */
  232. function clearAutoplay() {
  233. if (autoplayTimer != 0) {
  234. clearInterval(autoplayTimer);
  235. autoplayTimer = 0;
  236. }
  237. }
  238. /**
  239. * 启动自动轮播
  240. */
  241. function startAutoplay() {
  242. if (props.list.length <= 1) return;
  243. if (props.autoplay) {
  244. clearAutoplay();
  245. // 只有在非触摸状态下才启动自动轮播
  246. if (!isTouching.value) {
  247. isAnimating.value = true;
  248. // @ts-ignore
  249. autoplayTimer = setInterval(() => {
  250. // 再次检查是否在触摸中,避免触摸时自动切换
  251. if (!isTouching.value) {
  252. if (activeIndex.value >= props.list.length - 1) {
  253. activeIndex.value = 0;
  254. } else {
  255. activeIndex.value++;
  256. }
  257. }
  258. }, props.interval);
  259. }
  260. }
  261. }
  262. /**
  263. * 处理触摸开始事件
  264. * 记录触摸起始状态,准备手势识别
  265. * @param e 触摸事件对象
  266. */
  267. function onTouchStart(e: TouchEvent) {
  268. // 如果禁用触摸,则不进行任何操作
  269. if (props.disableTouch) return;
  270. // 单项或空列表不支持滑动
  271. if (props.list.length <= 1) return;
  272. // 设置触摸状态
  273. isTouching.value = true;
  274. // 清除自动轮播
  275. clearAutoplay();
  276. // 禁用动画,开始手势跟踪
  277. isAnimating.value = false;
  278. touchStartPoint.value = e.touches[0].clientX;
  279. touchStartTimestamp.value = Date.now();
  280. initialOffset.value = slideOffset.value;
  281. }
  282. /**
  283. * 处理触摸移动事件
  284. * 实时更新容器位置,实现跟手效果
  285. * @param e 触摸事件对象
  286. */
  287. function onTouchMove(e: TouchEvent) {
  288. if (props.list.length <= 1 || props.disableTouch || !isTouching.value) return;
  289. // 计算手指移动距离,实时更新偏移量
  290. const deltaX = e.touches[0].clientX - touchStartPoint.value;
  291. slideOffset.value = initialOffset.value + deltaX;
  292. }
  293. /**
  294. * 处理触摸结束事件
  295. * 根据滑动距离和速度判断是否切换轮播项
  296. */
  297. function onTouchEnd() {
  298. if (props.list.length <= 1 || !isTouching.value) return;
  299. // 重置触摸状态
  300. isTouching.value = false;
  301. // 恢复动画效果
  302. isAnimating.value = true;
  303. // 计算滑动距离、时间和速度
  304. const deltaX = slideOffset.value - initialOffset.value;
  305. const deltaTime = Date.now() - touchStartTimestamp.value;
  306. const velocity = deltaTime > 0 ? Math.abs(deltaX) / deltaTime : 0; // px/ms
  307. let newIndex = activeIndex.value;
  308. // 使用当前项的实际宽度进行滑动判断
  309. const currentSlideWidth = getSlideWidth(activeIndex.value);
  310. // 判断是否需要切换:滑动距离超过30%或速度够快
  311. if (Math.abs(deltaX) > currentSlideWidth * 0.3 || velocity > 0.3) {
  312. // 向右滑动且不是第一项 -> 上一项
  313. if (deltaX > 0 && activeIndex.value > 0) {
  314. newIndex = activeIndex.value - 1;
  315. }
  316. // 向左滑动且不是最后一项 -> 下一项
  317. else if (deltaX < 0 && activeIndex.value < props.list.length - 1) {
  318. newIndex = activeIndex.value + 1;
  319. }
  320. }
  321. // 更新索引 - 如果索引没有变化,需要手动恢复位置
  322. if (newIndex == activeIndex.value) {
  323. // 索引未变化,恢复到正确位置
  324. updateSlidePosition();
  325. } else {
  326. // 索引变化,watch会自动调用updateSlidePosition
  327. activeIndex.value = newIndex;
  328. }
  329. // 恢复自动轮播
  330. setTimeout(() => {
  331. startAutoplay();
  332. }, 300);
  333. }
  334. /**
  335. * 处理轮播项点击事件
  336. * @param index 被点击的轮播项索引
  337. */
  338. function handleSlideClick(index: number) {
  339. emit("item-tap", index);
  340. }
  341. /** 监听激活索引变化 */
  342. watch(activeIndex, (val: number) => {
  343. updateSlidePosition();
  344. emit("change", val);
  345. });
  346. onMounted(() => {
  347. getRect();
  348. startAutoplay();
  349. });
  350. </script>
  351. <style lang="scss" scoped>
  352. .cl-banner {
  353. @apply relative z-10 rounded-xl;
  354. &__list {
  355. @apply flex flex-row h-full w-full overflow-visible;
  356. // HBuilderX 4.8.2 bug,临时处理
  357. width: 100000px;
  358. &.is-transition {
  359. transition-property: transform;
  360. transition-duration: 0.3s;
  361. }
  362. }
  363. &__item {
  364. @apply relative duration-200;
  365. transition-property: transform;
  366. &-image {
  367. @apply w-full h-full rounded-xl;
  368. }
  369. }
  370. &__dots {
  371. @apply flex flex-row items-center justify-center;
  372. @apply absolute bottom-3 left-0 w-full;
  373. &-item {
  374. @apply w-2 h-2 rounded-full mx-1;
  375. background-color: rgba(255, 255, 255, 0.3);
  376. transition-property: width, background-color;
  377. transition-duration: 0.3s;
  378. &.is-active {
  379. @apply bg-white w-5;
  380. }
  381. }
  382. }
  383. }
  384. </style>