cl-banner.uvue 10 KB

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