Vue3-封装轮播图的组件

1,844 阅读2分钟

前言


在Vue3项目中如何封装自己的轮播图组件呢?希望轮播图可以控制是否实现自动轮播,当鼠标悬停的时候停止自动轮播,鼠标离开轮播开始,点击左右切换或者是分页指示器可以切换图片

开始啦!

为什么封装

  • 为了迎合ES6模块化开发思想
  • 注册全局组件,为了更好的复用,需要用到的地方直接使用标签名即可

## 如何封装?

通过Vue3中的插件的方式注册全局组件,项目中的统一组件放到 src/components文件夹中新增一个carousel.vue文件中写代码

<template>
  <div class="xtx-carousel" @mouseenter="stop" @mouseleave="start">
    <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 @click="toggle(-1)" href="javascript:;" class="carousel-btn prev"><i class="iconfont icon-angle-left"></i></a>
    <!-- 下一张 -->
    <a @click="toggle(1)" 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, watch } from 'vue'
export default {
  name: 'XtxCarousel',
  props: {
    sliders: {
      type: Array,
      default: () => []
    },
    duration: {
      type: Number,
      default: 1000
    },
    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 }
    )
    const stop = () => {
      if (timer) clearInterval(timer)
    }
    const start = () => {
      if (props.sliders.length && props.autoPlay) {
        autoPlayFn()
      }
    }
    // 上一张下一张
    const toggle = step => {
      index.value += step
      if (index.value >= props.sliders.length) {
        index.value = 0
        return
      }
      if (index.value < 0) {
        index.value = props.sliders.length - 1
      }
    }
    // 组件消耗,清理定时器
    // onUnmounted(() => {
    //   if (timer.value) clearInterval(timer.value)
    // })
    return { index, start, stop, toggle }
  }
}
</script>

<style scoped lang="less">
.xtx-carousel {
  :deep(.carousel-btn.prev) {
    left: 270px;
  }
  :deep(.carousel-indicator) {
    padding-left: 250px;
  }
}
.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, 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>

注册全局组件

src/components中创建index.js文件

// 扩展vue原有的功能:全局组件,自定义指令,挂载原型方法,注意:没有全局过滤器。
// 这就是插件
// vue2.0插件写法要素:导出一个对象,有install函数,默认传入了Vue构造函数,Vue基础之上扩展
// vue3.0插件写法要素:导出一个对象,有install函数,默认传入了app应用实例,app基础之上扩展

import XtxCarousel from './xtx-carousel.vue'
export default {
  install (app) {
    // 在app上进行扩展,app提供 component directive 函数
    // 如果要挂载原型 app.config.globalProperties 方式
    app.component(XtxCarousel.name, XtxCarousel)
  }
}

然后再main.js文件中注册

import {
  createApp
} from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
// 导入 重置样式
import 'normalize.css'
// 导入全局样式
import '@/style/common.css'
// 字体图标
import '@/assets/icon/iconfont.css'
// 自定义的插件
import XtxUI from '@/components/library'

createApp(App).use(store).use(router).use(XtxUI).mount('#app')

使用演示

将全局组件需要的通过自定义属性传递过去,这里使用固定数据模拟一下。
可以在全局组件外层包裹一个div元素,控制轮播图组件的大小

代码如下:

<template>
  <div class="home-banner">
    <XtxCarousel :list="sliders" class="xtx-carousel" />
  </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
    })
    console.log(sliders)
    return { sliders }
  }
}
</script>
<style scoped lang="less">
.home-banner {
  width: 1240px;
  height: 500px;
  position: absolute;
  left: 0;
  top: 0;
  z-index: 98;
}
.xtx-carousel {
  :deep(.carousel-btn.prev) {
    left: 270px;
  }
  :deep(.carousel-indicator) {
    padding-left: 250px;
  }
}
</style>