vue3封装轮播图组件

第一步:我们先来封装一个轮播图组件的通用组件:

(1)轮播图组件的结构 carousel.vue

<template>
  <div class='xtx-carousel'>
    <ul class="carousel-body">
     // 放置图片
      <li class="carousel-item fade">
        <RouterLink to="/">
          <img src="http://yjy-xiaotuxian-dev.oss-cn-beijing.aliyuncs.com/picture/2021-04-15/1ba86bcc-ae71-42a3-bc3e-37b662f7f07e.jpg" alt="">
        </RouterLink>
      </li>
    </ul>
    // 左右箭头
    <a href="javascript:;" class="carousel-btn prev"><i class="iconfont icon-angle-left"></i></a>
    <a href="javascript:;" class="carousel-btn next"><i class="iconfont icon-angle-right"></i></a>
   // 指示小圆点
     <div class="carousel-indicator">
      <span v-for="i in 5" :key="i"></span>
    </div>
  </div>
</template>
 
<script>
export default {
  name: 'XtxCarousel'
}
</script>
<style scoped lang="less">
.xtx-carousel{
  width: 100%;
  height: 100%;
  min-width: 300px;
  min-height: 150px;
  position: relative;
  .carousel{
    &-body {
      width: 100%;
      height: 100%;
    }
    &-item {
      width: 100%;
      height: 100%;
      position: absolute;
      left: 0;
      top: 0;
      opacity: 0;
      transition: opacity 0.5s linear;
      &.fade {
        opacity: 1;
        z-index: 1;
      }
      img {
        width: 100%;
        height: 100%;
      }
    }
    &-indicator {
      position: absolute;
      left: 0;
      bottom: 20px;
      z-index: 2;
      width: 100%;
      text-align: center;
      span {
        display: inline-block;
        width: 12px;
        height: 12px;
        background: rgba(0,0,0,0.2);
        border-radius: 50%;
        cursor: pointer;
        ~ span {
          margin-left: 12px;
        }
        &.active {
          background:  #fff;
        }
      }
    }
    &-btn {
      width: 44px;
      height: 44px;
      background: rgba(0,0,0,.2);
      color: #fff;
      border-radius: 50%;
      position: absolute;
      top: 228px;
      z-index: 2;
      text-align: center;
      line-height: 44px;
      opacity: 0;
      transition: all 0.5s;
      &.prev{
        left: 20px;
      }
      &.next{
        right: 20px;
      }
    }
  }
  &:hover {
    .carousel-btn {
      opacity: 1;
    }
  }
}
</style>


(2) 然后我们全局注册轮播图插件,在index.js中

 
import Carousel from './carousel.vue'
 
export default {
  install (app) {
   app.component(Carousel.name, XtxCarousel)
  }
}


注:在Vue3中注册全局插件时,install的参数不在是vue而是app

(3)在main.js注册这个插件(导入并挂载)

import XxxUI from '@/xxx/index.js'
createApp(App)
  .use(store)
  .use(router)
  .use(XxxUI)
  .mount('#app')


这样我们就得到一个全局都可以使用的轮播图的插件了

第二步:使用轮播图插件

定义一个使用轮播图的插件:如banner.vue

<template>
  <div class="home-banner">
    <Carousel />
  </div>
</template>
<script>
export default {
  name: 'HomeBanner'
}
</script>
<style scoped lang="less">
.home-banner {
  width: 1240px;
  height: 500px;
  position: absolute;
  left: 0;
  top: 0;
  z-index: 98
}
</style>


渲染数据

在home.vue组件中,调用接口,渲染数据,并把数据通过自定义属性传给子组件,轮播组件

<template>
  <div class="home-banner">
    <XtxCarousel :sliders="sliders" />
  </div>
</template>
<script>
import { ref } from 'vue'
import { findBanner } from '@/api/home'
export default {
  name: 'HomeBanner',
  setup () {
    const sliders = ref([])
    findBanner().then(data => {
    sliders.value = data.result
   })
    return { sliders }
  }
}
</script>


在轮播组件完成数据渲染

<template>
  <div class='xtx-carousel'>
    <ul class="carousel-body">
      <li class="carousel-item" v-for="(item,i) in sliders" :key="i" :class="{fade:index===i}">
        <RouterLink to="/">
          <img :src="item.imgUrl" alt="">
        </RouterLink>
      </li>
    </ul>
    <a href="javascript:;" class="carousel-btn prev"><i class="iconfont icon-angle-left"></i></a>
    <a href="javascript:;" class="carousel-btn next"><i class="iconfont icon-angle-right"></i></a>
    <div class="carousel-indicator">
      <span v-for="(item,i) in sliders" :key="i" :class="{active:index===i}"></span>
    </div>
  </div>
</template>
 
<script>
+import { ref } from 'vue'
export default {
  name: 'XtxCarousel',
  props: {
    sliders: {
      type: Array,
      default: () => []
    }
  },
  setup () {
    // 默认显示的图片的索引
    const index = ref(0)
    return { index }
  }
}
</script>


注:fade是控制显示那张图片的,需要一个默认索引数据,渲染第一张图和激活第一个点 

第三步:在轮播组件封装轮播的功能

包括:(1)自动轮播的功能

           (2)鼠标进入暂停轮播,鼠标离开开启轮播

          (3)点击左右按钮切换轮播图

(1)功能一:自动轮播功能:

父组件:banner组件

<template>
  <div class="home-banner">
    <!-- 轮播图组件 -->
    <!-- 在banner组件实现轮播业务 -->
    <!-- autoplay控制是否自动轮播  duration控制时间间隔-->
    <XtxCarousel :sliders="sliders" :autoplay="true" :duration="2" />
  </div>
</template>


轮播组件 :利用定时器

+import { ref, watch } from 'vue'
export default {
  name: 'XtxCarousel',
  props: {
    sliders: {
      type: Array,
      default: () => []
    },
    duration: {
      type: Number,
      default: 3000
    },
    autoPlay: {
      type: Boolean,
      default: false
    }
  },
  setup (props) {
    // 默认显示的图片的索引
    const index = ref(0)
    // 自动播放
    let timer = null
    const autoPlayFn = () => {
     clearInterval(timer)
      timer = setInterval(() => {
        index.value++
        if (index.value >= props.sliders.length) {
          index.value = 0
        }
      }, props.duration)
    }
    watch(() => props.sliders, (newVal) => {
      // 有数据&开启自动播放,才调用自动播放函数
      if (newVal.length > 1 && props.autoPlay) {
        index.value = 0
        autoPlayFn()
      }
    }, { immediate: true })

    return { index }
  }
}
     (2)功能二:鼠标进入暂停轮播,鼠标离开开启轮播  

<template>
 <div class="xtx-carousel" @mouseenter="stop" @mouseleave="start">
    <!-- 轮播图图片列表 -->
    <ul class="carousel-body">
      <li v-for="(item, i) in sliders" :key="item.id" class="carousel-item " :class="{ fade: index === i }">
        <RouterLink to="/">
          <img :src="item.imgUrl" alt="" />
        </RouterLink>
      </li>
    </ul>
 
    <!-- 左右两侧的小箭头 -->
    <a href="javascript:;" class="carousel-btn prev"><i class="iconfont icon-angle-left"></i></a>
    <a href="javascript:;" class="carousel-btn next"><i class="iconfont icon-angle-right"></i></a>
    <!-- 中间的指示器:5个小圆点 -->
    <div class="carousel-indicator">
      <span :class="{ active: index === i - 1 }" v-for="i in sliders.length" :key="i"></span>
    </div>
  </div>
</template>
 
<script>
import { ref, watch } from 'vue'
export default {
  name: 'XtxCarousel',
  props: {
    sliders: {
      type: Array,
      default: () => []
    },
    autoplay: {
      type: Boolean,
      default: true
    },
    duration: {
      type: Number,
      default: 2
    }
  },
  setup(props) {
    // 控制当前的索引
    const index = ref(0)
    const timer = ref(null)
    // 封装一个自动轮播的函数
    const autoplayFn = () => {
      // 防止触发多个定时任务
      clearInterval(timer.value)
      timer.value = setInterval(() => {
        index.value += 1
        if (index.value >= props.sliders.length) {
          // 超过右侧范围,从头开始
          index.value = 0
        }
      }, props.duration * 1000)
    }
    // 侦听器也可以侦听props的数据
    watch(
      () => props.sliders,
      () => {
        // 轮播图长度大于1并且标志位是放开的
        if (props.sliders.length > 1 && props.autoplay) {
          autoplayFn()
        }
      },
      { immediate: true }
    )
    // 进入控制暂停轮播
    const stop = () => {
      if (timer.value) {
       clearInterval(timer.value)
      }
    }
    // 离开开始轮播
    const start = () => {
      if (props.sliders.length > 1 && props.autoplay) {
        autoplayFn()
      }
    }
    return { index, stop, start }
  }
}
</script>
<style scoped lang="less">
.xtx-carousel {
  width: 100%;
  height: 100%;
  min-width: 300px;
  min-height: 150px;
  position: relative;
  .carousel {
    &-body {
      width: 100%;
      height: 100%;
    }
    &-item {
      width: 100%;
      height: 100%;
      position: absolute;
      left: 0;
      top: 0;
      opacity: 0;
      transition: opacity 0.5s linear;
      // fade决定那张图显示
      &.fade {
        opacity: 1;
        z-index: 1;
      }
      img {
        width: 100%;
        height: 100%;
      }
    }
    &-indicator {
      position: absolute;
      left: 0;
      bottom: 20px;
      z-index: 2;
      width: 100%;
      text-align: center;
      span {
        display: inline-block;
        width: 12px;
        height: 12px;
        background: rgba(0, 0, 0, 0.2);
        border-radius: 50%;
        cursor: pointer;
        ~ span {
          margin-left: 12px;
        }
        &.active {
          background: #fff;
        }
      }
    }
    &-btn {
      width: 44px;
      height: 44px;
      background: rgba(0, 0, 0, 0.2);
      color: #fff;
      border-radius: 50%;
      position: absolute;
      top: 228px;
      z-index: 2;
      text-align: center;
      line-height: 44px;
      opacity: 0;
      transition: all 0.5s;
      &.prev {
        left: 20px;
      }
      &.next {
        right: 20px;
      }
    }
  }
  &:hover {
    .carousel-btn {
      opacity: 1;
    }
  }
}
</style>


(3)功能三:点击左右按钮切换轮播图


 性能优化:在切换到其他组件时,销毁轮播图组件,使用onUnmounted

// 组件消耗,清理定时器
onUnmounted(() => {
    clearInterval(timer)
})

原文链接  Vue3---封装一个轮播图组件_丹丹呀~~的博客-CSDN博客_vue封装无缝滚动轮播图组件

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是一个简单的 Vue2 轮播图组件封装: ```vue <template> <div class="slider"> <div class="slider__wrapper" :style="{ transform: 'translateX(' + translateX + 'px)' }"> <div v-for="(item, index) in items" :key="index" class="slider__item"> <img :src="item.imgUrl" alt=""> </div> </div> <div class="slider__dots"> <span v-for="(item, index) in items" :key="index" :class="{ active: currentIndex === index }" @click="handleDotClick(index)"></span> </div> <button class="slider__btn slider__btn--prev" @click="prev"> <i class="iconfont icon-arrow-left"></i> </button> <button class="slider__btn slider__btn--next" @click="next"> <i class="iconfont icon-arrow-right"></i> </button> </div> </template> <script> export default { props: { items: { type: Array, required: true }, interval: { type: Number, default: 3000 } }, data() { return { currentIndex: 0, translateX: 0, timer: null } }, computed: { wrapperWidth() { return this.items.length * 100 + '%' }, itemWidth() { return 100 / this.items.length + '%' } }, mounted() { this.startAutoPlay() }, beforeDestroy() { this.stopAutoPlay() }, methods: { startAutoPlay() { this.timer = setInterval(() => { this.next() }, this.interval) }, stopAutoPlay() { clearInterval(this.timer) }, prev() { this.currentIndex = (this.currentIndex + this.items.length - 1) % this.items.length this.translateX = -this.currentIndex * this.$el.clientWidth }, next() { this.currentIndex = (this.currentIndex + 1) % this.items.length this.translateX = -this.currentIndex * this.$el.clientWidth }, handleDotClick(index) { this.currentIndex = index this.translateX = -this.currentIndex * this.$el.clientWidth } } } </script> <style> .slider { position: relative; overflow: hidden; } .slider__wrapper { display: flex; transition: transform 0.3s ease-out; } .slider__item { width: 100%; flex-shrink: 0; } .slider__dots { position: absolute; bottom: 20px; left: 50%; transform: translateX(-50%); display: flex; } .slider__dots span { width: 10px; height: 10px; border-radius: 50%; background-color: #ccc; margin-right: 5px; cursor: pointer; transition: background-color 0.3s ease-out; } .slider__dots span.active { background-color: #333; } .slider__btn { position: absolute; top: 50%; transform: translateY(-50%); width: 30px; height: 30px; background-color: rgba(0, 0, 0, 0.3); border: none; border-radius: 50%; color: #fff; cursor: pointer; transition: background-color 0.3s ease-out; } .slider__btn:hover { background-color: rgba(0, 0, 0, 0.5); } .slider__btn i { font-size: 16px; line-height: 30px; } .slider__btn--prev { left: 20px; } .slider__btn--next { right: 20px; } </style> ``` 使用时,可在父组件中引入并传入轮播图数据: ```vue <template> <slider :items="items" :interval="3000" /> </template> <script> import Slider from '@/components/Slider.vue' export default { components: { Slider }, data() { return { items: [ { imgUrl: 'https://picsum.photos/800/400?random=1' }, { imgUrl: 'https://picsum.photos/800/400?random=2' }, { imgUrl: 'https://picsum.photos/800/400?random=3' } ] } } } </script> ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值