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

Solution to input cursor misalignment in Chrome, Firefox, and IE

Detailed explanation of the misplacement of the in...

Teach you how to use Portainer to manage multiple Docker container environments

Table of contents Portainer manages multiple Dock...

MySQL 5.6.33 installation and configuration tutorial under Linux

This tutorial shares the installation and configu...

MySQL index optimization: paging exploration detailed introduction

Table of contents MySQL Index Optimization Paging...

How to build Git service based on http protocol on VMware+centOS 8

Table of contents 1. Cause 2. Equipment Informati...

Detailed explanation of crontab scheduled execution command under Linux

In LINUX, periodic tasks are usually handled by t...

Using Docker+jenkins+python3 environment to build a super detailed tutorial

Preface: After the automation is written, it need...

How to use TypeScript in Vue

introduction In recent years, the call for TypeSc...

Detailed explanation of the Sidecar mode in Docker Compose

Table of contents What is Docker Compose Requirem...

JavaScript to achieve lottery effect

This article shares the specific code of JavaScri...

Example of using CSS3 to customize the style of input multiple-select box

Principle: First hide the input element, then use...

Summary of Common Mistakes in Web Design

In the process of designing a web page, designers...

How to install lua-nginx-module module in Nginx

ngx_lua_module is an nginx http module that embed...

Commands to find domain IP address in Linux terminal (five methods)

This tutorial explains how to verify the IP addre...

Implementation of Docker CPU Limit

1. --cpu=<value> 1) Specify how much availa...