cl-banner.uvue 11 KB

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