How to encapsulate the carousel component in Vue3

How to encapsulate the carousel component in Vue3

Purpose

Encapsulate the carousel component and use it directly. The specific contents are as follows

General steps

  • Prepare the basic layout of my-carousel component and register it globally
  • Prepare the home-banner component, use the my-carousel component, and register it on the home page.
  • Deep-scope selectors override the default styles of the my-carousel component
  • Get the carousel data in the home-banner component and pass it to the my-carousel component
  • When the my-carousel component is finished rendering
  • Autoplay, expose the auto-rotate attribute, set it to automatically rotate
  • If there is automatic playback, enter, leave, pause, start
  • Indicator switch, previous, next
  • Destroy components and clean up timers

Landing code

1. Packaging components

<template>
  <div class="my-carousel" @mouseenter="stop" @mouseleave="start">
    <ul class="carousel-body">
      <li v-for="(item, i) in findBannerList" :key="item.id" class="carousel-item" :class="{ fade: index === i }">
        <RouterLink to="/">
          <img :src="item.imgUrl" alt="Picture" />
        </RouterLink>
      </li>
    </ul>
    <a @click="clickFn(-1)" href="javascript:;" class="carousel-btn prev"><i class="iconfont icon-angle-left"></i></a>
    <a @click="clickFn(1)" href="javascript:;" class="carousel-btn next"><i class="iconfont icon-angle-right"></i></a>
    <div class="carousel-indicator">
      <span @click="active(i)" v-for="(item, i) in findBannerList" :key="i" :class="{ active: index === i }"></span>
    </div>
  </div>
</template>

<script>
import { onUnmounted, ref, watch } from 'vue'
export default {
  name: 'Carousel',
  props: {
    findBannerList: {
      type: Array,
      default: () => []
    },
    autoplay:
      type: Boolean,
      default: true
    },
    duration: {
      type: Number,
      default: 3
    }
  },
  setup(props) {
    const index = ref(0)
    // Define a constant storage timer const timer = ref(null)
    // Timer method to achieve automatic carousel effect const autoplayFn = () => {
      // Anti-shake, to prevent multiple triggering of the timer clearInterval(timer.value)
      timer.value = setInterval(() => {
        index.value += 1
        if (index.value >= props.findBannerList.length) {
          index.value = 0
        }
      }, props.duration * 1000)
    }
    // Listener, according to the data returned by the interface and the related attribute parameters passed, autoplay starts the carousel // Listen to the length of the returned data, when the length is greater than 1 and autoplay is true, start the carousel watch(
      () => props.findBannerList,
      () => {
        if (props.findBannerList.length > 1 && props.autoplay) {
          autoplayFn()
        }
      }
    )
    // Move the mouse into the carousel to stop automatic playback const stop = () => {
      if (timer.value) clearInterval(timer.value)
    }
    // Move the mouse out of the carousel and start the timer const start = () => {
      if (props.findBannerList.length > 1 && props.autoplay) {
        autoplayFn()
      }
    }
    // Click the left and right buttons on the carousel to switch the carousel. The parameters passed in determine whether the carousel moves left or right. const clickFn = e => {
      index.value += e
      if (index.value >= props.findBannerList.length) {
        index.value = 0
      }
      if (index.value < 0) {
        index.value = props.findBannerList.length - 1
      }
    }
    // Click the indicator (the small dot under the carousel) to switch the carousel const active = e => {
      index.value = e
    }
    //Love letter timer when component is destroyed to avoid performance loss onUnmounted(() => {
      if (timer.value) clearInterval(timer.value)
    })
    return { index, stop, start, clickFn, active }
  }
}
</script>
<style scoped lang="less">
.my-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>

2. Packaging into plugins

import MyCarousel from './my-carousel.vue'
export default {
  install(app) {
    app.component(MyCarousel.name, MyCarousel)
  }
}

3. Global registration in the entry file main.js

import { createApp } from 'vue'
import App from './App.vue'
import MyUI from './components/library'

// To use the plugin, use app.use(plugin) in main.js
createApp(App).use(MyUI).mount('#app')

4. Using components in your project

Prepare the home-banner component, use the my-carousel component, and then introduce the home-banner component where the carousel is used in the project. The following parameters can be set in the home-banner component

The findBannerList parameter is used as the background request data to be given to the component

Whether the autoplay parameter enables the carousel. The default value is true. Enable the carousel.

The duration parameter is the time interval of the carousel in seconds.

<template>
  <div class="home-banner">
    <MyCarousel :findBannerList="findBannerList" :autoplay="true" :duration="3" />
  </div>
</template>

Summarize

Just follow the ideas and steps and implement it step by step.

1. Basic component splitting and layout
2. Automatic carousel
3. Hover control to start and stop
4. Manual control switching
5. Destroy the timer
6. Extract relevant parameters

The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM.

You may also be interested in:
  • Vue3.0 handwritten carousel effect
  • vue+rem custom carousel effect
  • Sample code of uniapp vue and nvue carousel components

<<:  Detailed tutorial for springcloud alibaba nacos linux configuration

>>:  Troubleshooting the reasons why MySQL deleted records do not take effect

Recommend

Centos8 (minimum installation) tutorial on how to install Python3.8+pip

After minimizing the installation of Python8, I i...

Example of how to increase swap in CentOS7 system

Preface Swap is a special file (or partition) loc...

MySQL 8.0.20 installation and configuration detailed tutorial

This article shares with you a detailed tutorial ...

Detailed explanation of the use of JavaScript functions

Table of contents 1. Declare a function 2. Callin...

Solve the problem of specifying udp port number in docker

When Docker starts a container, it specifies the ...

MySQL query method with multiple conditions

mysql query with multiple conditions Environment:...

Detailed explanation of MySQL custom functions and stored procedures

Preface This article mainly introduces the releva...

MySQL 8.0 WITH query details

Table of contents Learning about WITH queries in ...

Minimalistic website design examples

Web Application Class 1. DownForEveryoneOrJustMe ...

Detailed analysis of the usage and application scenarios of slots in Vue

What are slots? We know that in Vue, nothing can ...

How to reset the root password of Mysql in Windows if you forget it

My machine environment: Windows 2008 R2 MySQL 5.6...

Basic concepts and common methods of Map mapping in ECMAScript6

Table of contents What is a Mapping Difference be...