Steps to encapsulate the carousel component in vue3.0

Steps to encapsulate the carousel component in vue3.0

Following the previous article, we will become familiar with the basic usage of vue3.0, and after using it for a period of time, we will start to prepare to develop a PC component library suitable for vue3.0. I will continue to update the writing methods and precautions of some component libraries. Students who are interested can pay more attention to it. Without further ado, let’s get started.

Develop a carousel component, suitable for PC (no app is considered yet), used in vue3.0 + TS

The general effect is as follows:

Free image carousel, corresponding dot image jump, left and right indicator jump, etc. Expose the following options configuration:

The above are the main options. Let's expand on how to encapsulate them.

1: Encapsulation idea

The core idea of ​​encapsulating components in vue3.0 and vue2.0 is actually the same. You need to use vue.component(); to register the component, and then mount it in main.ts to use it.

Create under src: src --> libs --> sqm_ui (the name of your own UI library) --> index.js

The index.js here is the entry point for registering components.

Create a new file in the same directory, Carousel, which contains all the functions and styles of the carousel component.

The directory is as follows:

One thing to note: Although it is used in vue3.0 and ts, the entry file still uses js, which is also to adapt to non-ts writing methods.

In index.js:

import Carousel from './Carousel/carousel';
import CarItem from './Carousel/item'; let SqmUI = {};
SqmUI.install = function(vue) {
 vue.component(Carousel.name, Carousel);
 vue.component(CarItem.name,CarItem);
};
export default SqmUI;

However, in order to use it with TS, we need to create a new index.d.ts file to describe the member types in the library for TS to use.

declare const _default: ({
 install: (app: import("vue").App<any>, ...options: any[]) => any; // Here is a simple description of install});
export default _default;

After completing the above configuration, use it in main.ts:

import SqmUI from '@/libs/sqm_ui/index';
import { createApp } from 'vue';
createApp.use(SqmUI);

2. Packaging process

For the carousel, we need a fixed container to place each scrolling picture. At this time, we need to define a Carousel.vue component.

<template>
 <div class="carousel">
 <slot></slot> // The slot here is used to place the item component</div>
</template>

You also need a component to store photos, item.vue

<template>
 <div class="carousel-item">
 <slot></slot> // The slot here is used to place img
 </div>
</template>

The basic framework is set up, and when users use it, they configure options in the carousel.

<carousel
 :autoPlay="true" 
 :durdation="3000" 
 :initial="3" 
 :hasDot="true" 
 :hasDirector="true"> </carousel>

In carousel.vue: accept the passed configuration items

props: { 
 autoplay:  
 type: Boolean,  
 default: true }, 
 duration: {  
 type: Number,  
 default: 3000 }, 
 initial: {  
 type: Number,  
 default: 0 }, 
 hasDot: {  
 type: Boolean,
 default: true }, 
 hasDirector: { 
 type: Boolean,  
 default: true }
}

(1): Implement autoPlay:

In carousel.vue:

const autoPlay = () => {
 if (props.autoplay) {
 t = setInterval(() => {
  // Carousel logic}, props.duration);
};
onMounted(() => {
 autoPlay();
});

The logic is very simple. Define an autoPlay function and mount it in the mounted phase.

(2): Implement carousel:

Think about this question: How can I make this picture appear? The index of the current image must be equal to the index during the carousel in order to be displayed.

In item.vue:

<div class="carsel-item" v-if="selfIndex === currentIndex"> 
 <slot></slot> 
</div>

It can only be displayed when its own index is equal to the current index.

Get currentIndex:

Built-in method in vue3.0: getCurrentInstance()

This is a very important method. Through this method we can get the instance of the current component, and then get the context of the component through ctx. Very easy to use.

In item.vue:

setup() {
 const instance:any = getCurrentInstance(); console.log(instance);
}

Under instance.vnode, there is a key which is the key of each image, that is, the index.

There is a currentIndex defined under instance.parent.ctx, which is the current index.

When the two are the same, the current picture can be displayed. So where is currentIndex set?

Back to carousel.vue:

setup(props) { 
 const state = reactive({  
 currentIndex: props.initial,  
 itemLen: 0,  
 showDir: false 
 });
}

The current currentIndex is the value of the passed initial.

In autoPlay: Execute the carousel

const setIndex = ((dir:String): void => { 
 switch(dir) { 
 case 'next':  
  state.currentIndex += 1;  
  if (state.currentIndex === state.itemLen) {   
  state.currentIndex = 0;  
  }  
  break; 
 case 'prev':  
  state.currentIndex -= 1;  
  if (state.currentIndex === -1) {   
  state.currentIndex = state.itemLen - 1;  
  }  
  break; 
 default:  
  break; 
 } 
});

When next, let currentIndex++; until it is equal to the length of the carousel image. (array.length)

When prev, let currentIndex--; until === -1

Then listen in item.vue:

watch(() => {  
 return instance.parent.ctx.currentIndex 
 }, (value) => {  
 state.currentIndex = value; 
})

This completes the image carousel.

Three: Dot indicator

The idea of ​​implementation is still very simple:

The hasDot passed in is used to determine whether it needs to be displayed. The passed itemlen determines how many dots to display based on the number of pictures. Clicking a dot will jump to the corresponding picture.

In dot.vue:

<template>
 <div class="dot-goes-wrapper" v-if="hasDot">
 <div class="dot-item" v-for="item in itemLen" :key="item">
 <a href="javascript:;" rel="external nofollow" rel="external nofollow" rel="external nofollow" 
  class="dot-link"
  :style="{backgroundColor: (item - 1) === currentIndex ? dotBgColor : '#fff'}" 
  @click="dotClick(item - 1)">
 </a> 
 </div> 
 </div>
</template>
<script lang="ts">
import {defineComponent} from 'vue';
export default defineComponent({
 name: 'dot',
 props: { 
 itemLen: Number, 
 currentIndex: Number, 
 dotBgColor: {  
  type: String,
  default: '#ff5000' },
 hasDot: {  
  type: Boolean,  
  default: true } 
 }, 
 setup(props, ctx) { 
 const dotClick = (index: Number) => { 
  ctx.emit('dotClick', index); 
 }; 
 return {  
  dotClick 
 } 
}})
</script>

Trigger the dotClick event through ctx, pass in the index, and use it in the parent component (Carousel.vue):

@dotClick="dotClick"

const dotClick = (index: any): void => {

state.currentIndex = index;

};

This completes the dot indicator.

Four: Left and right indicators

This is very simple, just display it when moving in, and then click on the picture to slide.

<template> 
 <div v-if="showDir"> 
 <div class="director dir-next" v-if="dir === 'next'">  
  <a href="javascript:;" rel="external nofollow" rel="external nofollow" rel="external nofollow" @click="dirClick(dir)">&gt;</a> 
 </div> 
 <div class="director dir-prev" v-else-if="dir === 'prev'">  
  <a href="javascript:;" rel="external nofollow" rel="external nofollow" rel="external nofollow" @click="dirClick(dir)">&lt;</a> 
 </div> 
 </div>
</template>

<script lang="ts">
import {defineComponent} from 'vue';
export default defineComponent({ 
 name: 'direct', 
 props: { 
 dir: String, 
 showDir: {  
  type: Boolean,  
  default: false 
 } 
 }, 
 setup(props, ctx) { 
 const dirClick = (dir: String) => {  
  ctx.emit('dirClick', dir); 
 }; 
 return {  
  dirClick 
 } 
 }
})</script>

Similarly, a dirClick event is passed to the parent component, and click-move is executed in the parent component.

Five: Finally:

Because the carousel is implemented by a timer, the timer needs to be destroyed.

onBeforeUnmount(() => {

      _clearFunction();

});

function _clearFunction(): void {

     clearInterval(t);

       t = null;

};

Stop autoplay on mouse-in, and show left and right indicators:

const mouseEnter = (): void => { 
 _clearFunction();
 state.showDir = true;
 }; 

Start playing when the mouse moves out, and the left and right indicators disappear

 const mouseLeave = (): void => { 
  autoPlay();
  state.showDir = false; 
};

ok. This is the general idea. There are some details that you can think about more. grateful! !

VI: Review of past issues

www.jb51.net/article/206833.htm

The above is the detailed content of the steps for encapsulating the carousel component in vue3.0. For more information about encapsulating the carousel component in vue3.0, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • Using better-scroll in Vue to implement the carousel component
  • Detailed explanation of how to use the vue.js carousel component
  • Vue2 slide component example code
  • Vue's carousel component implementation method
  • Detailed explanation of reusable carousel component in Vue2
  • Implementing carousel chart based on vue.js carousel component vue-awesome-swiper
  • How to encapsulate the carousel component in Vue3

<<:  Detailed explanation of dynamic link library calling C/C++ method in Python in Ubuntu

>>:  MySQL replication detailed explanation and simple example

Recommend

Solutions to browser interpretation differences in size and width and height in CSS

Let’s look at an example first Copy code The code ...

Vue realizes screen adaptation of large screen pages

This article shares the specific code of Vue to a...

Native JS realizes compound motion of various motions

This article shares with you a compound motion im...

Reasons and methods for Waiting for table metadata lock in MySQL

When MySQL performs DDL operations such as alter ...

Detailed explanation of Excel parsing and exporting based on Vue

Table of contents Preface Basic Introduction Code...

Vue routing to implement login interception

Table of contents 1. Overview 2. Routing Navigati...

MySQL slow log online problems and optimization solutions

MySQL slow log is a type of information that MySQ...

CSS3 uses the transition property to achieve transition effects

Detailed description of properties The purpose of...

Solutions to Mysql index performance optimization problems

The optimization created by MySQL is to add index...

Analysis of Nginx Rewrite usage scenarios and configuration methods

Nginx Rewrite usage scenarios 1. URL address jump...

How to use Docker to build OpenLDAP+phpLDAPadmin unified user authentication

1. Background Use LDAP to centrally manage operat...