vue.js 3.2.6 解決swiper動態加載數據時默認顯示最后一頁(swiper@6.8.4)


一,關於(swiper動態加載數據時默認顯示最后一頁)網上的一些解決方法:

網上的主要的解決方法有兩個:

1是指定v-if為圖片數量,當圖片數量大於時才生成swiper,
 在swiper@6.8.4這個版本無效
2,在加載完數據后,用transform指定第一頁的內容移動一定的距離,

  例子:

          setTimeout(() => {
            document.getElementsByClassName('swiper-wrapper')[0].style.transform = 'translate3d(-375px, 0px, 0px)'
          }, 50)

   這個有效,但下面的Pagination指示器無效,而且用戶手動滑動時會出現不正常的移動

   這個改動方法不夠好

說明:劉宏締的架構森林是一個專注架構的博客,

網站:https://blog.imgtouch.com
本文: https://blog.imgtouch.com/index.php/2023/05/28/vue-js-3-2-6-jie-jue-swiper-dong-tai-jia-zai-shu-ju-shi-mo/

         對應的源碼可以訪問這里獲取: https://github.com/liuhongdi/
         或: https://gitee.com/liuhongdi

說明:作者:劉宏締 郵箱: 371125307@qq.com

 

二,編寫代碼:

解決方法:

    const onSwiper = (swiper) => {
      console.log('-----onSwiper begin slideTo:')
      swiper.updateSlides();
      swiper.slideTo(1, 0, false);
    }

指定滑動到第一頁就行了

例子:

Home.vue

<template>
  <div style="width:100%;height:100%;background: #00ff00;" ref="topdiv">
    <swiper @swiper="onSwiper"
            :autoplay="swiper_options.autoplay"
            :loop="swiper_options.loop"
            :speed="swiper_options.speed"
            :pagination="{ clickable: true }"
            :style="{height:swiperHeight+'px',background:'#ff0000'}">
      <template v-for="(slideItem,i) in slides" :key="i">
        <swiper-slide>
          <div style="width:100%;height:100%;display: flex;justify-content: center;align-items: center;">
            <img  :src="slideItem.homeSlideUrl" alt="" style="max-height: 100%;max-width: 100%;">
          </div>
        </swiper-slide>
      </template>
    </swiper>
<div style="display:flex;flex-direction: column;width:100%;">
  <template v-for="(homeItem,i) in homes" :key="i">
    <div style="width:100%;position:relative;">
      <img :src="homeItem.homeBackUrl" style="width:100%;" />
      <!--當前模塊:{{homeId}}<br/>-->
      <template v-for="(item,k) in homeItem.homeContentList" :key="k" >
        <div v-if="item.ptype===6" @click="golink(item.linkId)" :id="item.globalIndex" :style="{'opacity':'0.5','position':'absolute',left:(item.pleft/100)+'rem',top:(item.ptop/100)+'rem','width':(item.pwidth/100)+'rem','height':(item.pheight/100)+'rem','background':'#ff0000',}">
        </div>
        <div v-if="item.ptype===4" :id="item.globalIndex" :style="{background:'url('+item.videoCoverUrl+')','background-size':'100% auto','background-repeat':'no-repeat','position':'absolute',left:(item.pleft/100)+'rem',top:(item.ptop/100)+'rem','width':(item.pwidth/100)+'rem','height':(item.pheight/100)+'rem',}">
          <video :style="{'width':(item.pwidth/100)+'rem', 'height':(item.pheight/100)+'rem', background: '#ffffff'}"
                 muted="" autoplay="" playsinline="" webkit-playsinline=""
                 :poster="item.videoCoverUrl"
                 :src="item.videoUrl" controls="">
          </video>
        </div>
        <div v-if="item.ptype===5" @click="golink(item.linkId)" :id="item.globalIndex"
             :style="{background:'url('+item.imageUrl+')','background-size':'100% auto','background-repeat':'no-repeat','position':'absolute',left:(item.pleft/100)+'rem',top:(item.ptop/100)+'rem','width':(item.pwidth/100)+'rem','height':(item.pheight/100)+'rem',}">
        </div>
      </template>
    </div>
  </template>
</div>
  </div>
</template>

<script>
//,watch,nextTick
import { ref,reactive,onMounted} from "vue";
import {apiHome} from "../../api/api";

//引入swiper
import SwiperCore, { Autoplay, Pagination, EffectCoverflow,Navigation } from "swiper";
import { Swiper, SwiperSlide } from "swiper/vue";
import "swiper/swiper.min.css";
import "swiper/components/pagination/pagination.less";
import "swiper/components/navigation/navigation.less";
//設置swiper
SwiperCore.use([Autoplay, Pagination, EffectCoverflow,Navigation]);

export default {
  name: "Home",
    components: {
      Swiper,
      SwiperSlide,
    },
  setup() {
    //保存用戶數據的變量
    const msg = ref("");
    const domain = ref("");
    const loading = ref(true);
    const slides = ref([]);
    const homes = ref([]);
    const onSwiper = (swiper) => {
      console.log('-----onSwiper begin slideTo:')
      swiper.updateSlides();
      swiper.slideTo(1, 0, false);
    }

    //從接口獲取用戶信息
    const info = async () => {
      apiHome({
      }).then(res => {
        if (res.code == 0) {
          slides.value = res.data.slide;
          homes.value = res.data.list;
        }
      }).catch((error) => {
        console.log(error)
      })
    };
    info();

    //指定swiper的設置
    let swiper_options = reactive({
      initialSlide :1,
      autoplay:{
        delay:2000,
        disableOnInteraction: false
      },
      loop:true,
      speed:1000,
      autoHeight:true,
      pagination:{
        clickable: true
      },
    })

    const topdiv=ref(null);
    //指定swiper的高度,設置為寬度的62%
    const swiperHeight = ref(0);
    onMounted(() => {
      let width = topdiv.value.getBoundingClientRect().width;
      swiperHeight.value = width * 0.62;
    });

    const golink = (linkId) => {
      alert("商品Id:"+linkId);
    }

    return {
      info,
      msg,
      domain,
      loading,
      swiper_options,
      topdiv,
      swiperHeight,
      slides,
      homes,
      golink,
      onSwiper,
    };
  }
}
</script>

<style>
/*分頁用的圓點*/
.swiper-pagination-bullet {
  width: 8px;
  height: 8px;
  display: inline-block;
  border-radius: 50%;
  background: #fff;
  opacity: 0.6;

}
/*分頁用的圓點激活時*/
.swiper-pagination-bullet-active {
  opacity: 1;
  background: #fff;
}

.swiper-pagination {
  position: absolute;
  text-align: center;
  transition: 300ms opacity;
  transform: translate3d(0, 0, 0);
  z-index: 10;
}
.swiper-pagination-fraction, .swiper-pagination-custom, .swiper-container-horizontal > .swiper-pagination-bullets {
  bottom: 10px;
  left: 0;
  width: 100%;
}

.swiper-container-horizontal > .swiper-pagination-bullets .swiper-pagination-bullet {
  margin: 0 4px;
}

</style>

 

三,測試效果

頁面加載動態數據后swiper默認顯示最后一頁:

用slideTo指定后,默認顯示第一頁:

 

 

四,查看vue的版本:

liuhongdi@lhdpc:/data/vue/storeweb$ npm list vue
storeweb@0.1.0 /data/vue/storeweb
├─┬ @vue/cli-plugin-babel@4.5.13
│ └─┬ @vue/babel-preset-app@4.5.13
│   └── vue@3.2.6 deduped
├─┬ element-plus@1.1.0-beta.7
│ └── vue@3.2.6 deduped
├─┬ vue-router@4.0.11
│ └── vue@3.2.6 deduped
├── vue@3.2.6
└─┬ vue3-carousel@0.1.27
  └── vue@3.2.6 deduped

查看swiper的版本:

liuhongdi@lhdpc:/data/vue/storeweb$ npm list swiper
storeweb@0.1.0 /data/vue/storeweb
└── swiper@6.8.4

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM