<template>
  <div ref='swiperContainer' class='swiper-container'>
    <div class='swiper-wrapper'>
      <div class='swiper-slide' v-for='(item, index) in swiperList' :key='index'>
        <img :src='item.imgUrl' alt='' />
      </div>
    </div>
    <div class='swiper-pagination'></div>
  </div>
</template>
<script setup>
  import { ref, onMounted, onUnmounted } from 'vue'
  import Swiper from 'swiper'
  import 'swiper/swiper-bundle.css'

  const swiperContainer = ref(null)
  const swiperInstance = ref(null)
  const swiperList = ref([
    { imgUrl: 'https://picsum.photos/600/300/?image=0' },
    { imgUrl: 'https://picsum.photos/600/300/?image=1' },
    { imgUrl: 'https://picsum.photos/600/300/?image=2' },
    { imgUrl: 'https://picsum.photos/600/300/?image=3' },
    { imgUrl: 'https://picsum.photos/600/300/?image=4' }
  ])

  function initSwiper() {
    swiperInstance.value = new Swiper(swiperContainer.value, {
      loop: true,
      pagination: {
        el: '.swiper-pagination'
      }
    })
  }

  onMounted(() => {
    initSwiper()
  })

  function destroySwiper() {
    if (swiperInstance.value) {
      swiperInstance.value.destroy()
    }
  }

  function updateSwiper() {
    destroySwiper()
    initSwiper()
  }

  function handleResize() {
    updateSwiper()
  }

  window.addEventListener('resize', handleResize)

  function onDestroyed() {
    window.removeEventListener('resize', handleResize)
    destroySwiper()
  }

  onUnmounted(() => {
    onDestroyed()
  })

</script>
Vue3 Element Plus 轮播图组件:宽度百分百,高度600,Script Setup 代码

原文地址: https://www.cveoy.top/t/topic/mB9K 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录