cl-banner.uvue 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  1. <template>
  2. <view
  3. class="cl-banner"
  4. :class="[pt.className]"
  5. :style="{
  6. height: getUnit(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, getUnit } from "@/.cool";
  62. import type { PassThroughProps } from "../../types";
  63. import { useTouch } from "../../hooks";
  64. type Item = {
  65. url: string;
  66. isActive: boolean;
  67. };
  68. defineOptions({
  69. name: "cl-banner"
  70. });
  71. defineSlots<{
  72. item(props: { item: Item; index: number }): any;
  73. }>();
  74. const props = defineProps({
  75. // 透传属性
  76. pt: {
  77. type: Object,
  78. default: () => ({})
  79. },
  80. // 轮播项列表
  81. list: {
  82. type: Array as PropType<string[]>,
  83. default: () => []
  84. },
  85. // 上一个轮播项的左边距
  86. previousMargin: {
  87. type: Number,
  88. default: 0
  89. },
  90. // 下一个轮播项的右边距
  91. nextMargin: {
  92. type: Number,
  93. default: 0
  94. },
  95. // 是否自动轮播
  96. autoplay: {
  97. type: Boolean,
  98. default: true
  99. },
  100. // 自动轮播间隔时间(ms)
  101. interval: {
  102. type: Number,
  103. default: 5000
  104. },
  105. // 是否显示指示器
  106. showDots: {
  107. type: Boolean,
  108. default: true
  109. },
  110. // 是否禁用触摸
  111. disableTouch: {
  112. type: Boolean,
  113. default: false
  114. },
  115. // 高度
  116. height: {
  117. type: [Number, String],
  118. default: 160
  119. },
  120. // 图片模式
  121. imageMode: {
  122. type: String,
  123. default: "aspectFill"
  124. }
  125. });
  126. const emit = defineEmits(["change", "item-tap"]);
  127. const { proxy } = getCurrentInstance()!;
  128. const touch = useTouch();
  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: UniTouchEvent) {
  273. // 如果禁用触摸,则不进行任何操作
  274. if (props.disableTouch) return;
  275. // 单项或空列表不支持滑动
  276. if (props.list.length <= 1) return;
  277. // 注册触摸开始事件
  278. touch.start(e);
  279. // 设置触摸状态
  280. isTouching.value = true;
  281. // 清除自动轮播
  282. clearAutoplay();
  283. // 禁用动画,开始手势跟踪
  284. isAnimating.value = false;
  285. touchStartPoint.value = e.touches[0].clientX;
  286. touchStartTimestamp.value = Date.now();
  287. initialOffset.value = slideOffset.value;
  288. }
  289. /**
  290. * 处理触摸移动事件
  291. * 实时更新容器位置,实现跟手效果
  292. * @param e 触摸事件对象
  293. */
  294. function onTouchMove(e: UniTouchEvent) {
  295. if (props.list.length <= 1 || props.disableTouch || !isTouching.value) return;
  296. // 注册触摸移动事件
  297. touch.move(e);
  298. // 横向移动时才处理
  299. if (touch.horizontal != 1) {
  300. return;
  301. }
  302. // 计算手指移动距离,实时更新偏移量
  303. const deltaX = e.touches[0].clientX - touchStartPoint.value;
  304. slideOffset.value = initialOffset.value + deltaX;
  305. }
  306. /**
  307. * 处理触摸结束事件
  308. * 根据滑动距离和速度判断是否切换轮播项
  309. */
  310. function onTouchEnd() {
  311. if (props.list.length <= 1 || !isTouching.value) return;
  312. // 注册触摸结束事件
  313. touch.end();
  314. // 重置触摸状态
  315. isTouching.value = false;
  316. // 恢复动画效果
  317. isAnimating.value = true;
  318. // 计算滑动距离、时间和速度
  319. const deltaX = slideOffset.value - initialOffset.value;
  320. const deltaTime = Date.now() - touchStartTimestamp.value;
  321. const velocity = deltaTime > 0 ? Math.abs(deltaX) / deltaTime : 0; // px/ms
  322. let newIndex = activeIndex.value;
  323. // 使用当前项的实际宽度进行滑动判断
  324. const currentSlideWidth = getSlideWidth(activeIndex.value);
  325. // 判断是否需要切换:滑动距离超过30%或速度够快
  326. if (Math.abs(deltaX) > currentSlideWidth * 0.3 || velocity > 0.3) {
  327. // 向右滑动且不是第一项 -> 上一项
  328. if (deltaX > 0 && activeIndex.value > 0) {
  329. newIndex = activeIndex.value - 1;
  330. }
  331. // 向左滑动且不是最后一项 -> 下一项
  332. else if (deltaX < 0 && activeIndex.value < props.list.length - 1) {
  333. newIndex = activeIndex.value + 1;
  334. }
  335. }
  336. // 更新索引 - 如果索引没有变化,需要手动恢复位置
  337. if (newIndex == activeIndex.value) {
  338. // 索引未变化,恢复到正确位置
  339. updateSlidePosition();
  340. } else {
  341. // 索引变化,watch会自动调用updateSlidePosition
  342. activeIndex.value = newIndex;
  343. }
  344. // 恢复自动轮播
  345. setTimeout(() => {
  346. startAutoplay();
  347. }, 300);
  348. }
  349. /**
  350. * 处理轮播项点击事件
  351. * @param index 被点击的轮播项索引
  352. */
  353. function handleSlideClick(index: number) {
  354. emit("item-tap", index);
  355. }
  356. /** 监听激活索引变化 */
  357. watch(activeIndex, (val: number) => {
  358. updateSlidePosition();
  359. emit("change", val);
  360. });
  361. onMounted(() => {
  362. getRect();
  363. startAutoplay();
  364. });
  365. // 将触摸事件暴露给父组件,支持控制其它view将做touch代理
  366. defineExpose({
  367. onTouchStart,
  368. onTouchMove,
  369. onTouchEnd
  370. });
  371. </script>
  372. <style lang="scss" scoped>
  373. .cl-banner {
  374. @apply relative z-10 rounded-xl;
  375. &__list {
  376. @apply flex flex-row h-full w-full overflow-visible;
  377. // HBuilderX 4.8.2 bug,临时处理
  378. width: 100000px;
  379. transition-property: transform;
  380. }
  381. &__item {
  382. @apply relative duration-200;
  383. transition-property: transform;
  384. &-image {
  385. @apply w-full h-full rounded-xl;
  386. }
  387. }
  388. &__dots {
  389. @apply flex flex-row items-center justify-center;
  390. @apply absolute bottom-3 left-0 w-full;
  391. &-item {
  392. @apply w-2 h-2 rounded-full mx-1 border border-solid border-surface-500;
  393. background-color: rgba(255, 255, 255, 0.3);
  394. transition-property: width, background-color;
  395. transition-duration: 0.3s;
  396. &.is-active {
  397. @apply bg-white w-5;
  398. }
  399. }
  400. }
  401. }
  402. </style>