loop.js 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import { h } from 'vue';
  2. import Swiper from 'swiper';
  3. function calcLoopedSlides(slides, swiperParams) {
  4. let slidesPerViewParams = swiperParams.slidesPerView;
  5. if (swiperParams.breakpoints) {
  6. const breakpoint = Swiper.prototype.getBreakpoint(swiperParams.breakpoints);
  7. const breakpointOnlyParams = breakpoint in swiperParams.breakpoints ? swiperParams.breakpoints[breakpoint] : undefined;
  8. if (breakpointOnlyParams && breakpointOnlyParams.slidesPerView) {
  9. slidesPerViewParams = breakpointOnlyParams.slidesPerView;
  10. }
  11. }
  12. let loopedSlides = Math.ceil(parseFloat(swiperParams.loopedSlides || slidesPerViewParams, 10));
  13. loopedSlides += swiperParams.loopAdditionalSlides;
  14. if (loopedSlides > slides.length) {
  15. loopedSlides = slides.length;
  16. }
  17. return loopedSlides;
  18. }
  19. function renderLoop(swiperRef, slides, swiperParams) {
  20. const modifiedSlides = slides.map((child, index) => {
  21. if (!child.props) child.props = {};
  22. child.props.swiperRef = swiperRef;
  23. child.props['data-swiper-slide-index'] = index;
  24. return child;
  25. });
  26. function duplicateSlide(child, index, position) {
  27. if (!child.props) child.props = {};
  28. return h(child.type, { ...child.props,
  29. key: `${child.key}-duplicate-${index}-${position}`,
  30. class: `${child.props.className || ''} ${swiperParams.slideDuplicateClass} ${child.props.class || ''}`
  31. }, child.children);
  32. }
  33. if (swiperParams.loopFillGroupWithBlank) {
  34. const blankSlidesNum = swiperParams.slidesPerGroup - modifiedSlides.length % swiperParams.slidesPerGroup;
  35. if (blankSlidesNum !== swiperParams.slidesPerGroup) {
  36. for (let i = 0; i < blankSlidesNum; i += 1) {
  37. const blankSlide = h('div', {
  38. class: `${swiperParams.slideClass} ${swiperParams.slideBlankClass}`
  39. });
  40. modifiedSlides.push(blankSlide);
  41. }
  42. }
  43. }
  44. if (swiperParams.slidesPerView === 'auto' && !swiperParams.loopedSlides) {
  45. swiperParams.loopedSlides = modifiedSlides.length;
  46. }
  47. const loopedSlides = calcLoopedSlides(modifiedSlides, swiperParams);
  48. const prependSlides = [];
  49. const appendSlides = [];
  50. modifiedSlides.forEach((child, index) => {
  51. if (index < loopedSlides) {
  52. appendSlides.push(duplicateSlide(child, index, 'prepend'));
  53. }
  54. if (index < modifiedSlides.length && index >= modifiedSlides.length - loopedSlides) {
  55. prependSlides.push(duplicateSlide(child, index, 'append'));
  56. }
  57. });
  58. if (swiperRef.value) {
  59. swiperRef.value.loopedSlides = loopedSlides;
  60. }
  61. return [...prependSlides, ...modifiedSlides, ...appendSlides];
  62. }
  63. export { calcLoopedSlides, renderLoop };