code to swiper(轮播图demo)

83 阅读1分钟

code to swiper

轮播图demo: 最近看到很多面试手写轮播图,自己也手写了一个简单版本,有不足的jy们可以提提

html

<template>
    <div class="container">
        <div class="swiper">
            <div class="swiper_box" ref="swiper_box" @transitionend="handleTransitionEnd">
                <div class="swiper_item" v-for="item in extendedModels">
                    <img :src="item.src" alt="">
                </div>
            </div>
            <div class="pag" @mouseenter="mouseenter" @mouseleave="mouseleave">
                <span @click="checkPoint(index)" :key="item" v-for="(item, index) in dolist"
                    :class="['point', index == (selPoint % dolist) ? 'action' : '']"></span>
            </div>
        </div>
    </div>
</template>

js

<script lang="ts" setup>
import { computed, onMounted, ref } from 'vue';
import { models } from './models'

const dolist = computed(() => models.length)

const extendedModels = computed(() => [...models, models[0]])

const width = ref(400)
const imgW = width.value + 'px'
const selPoint = ref(0)
const swiper_box = ref<HTMLDivElement>()
const checkPoint = (i: number) => {
    swiper_box.value!.style.transition = 'transform 1s linear';
    swiper_box.value!.style.transform = `translateX(-${i * width.value}px)`
    selPoint.value = i
}


const handleTransitionEnd = () => {
    if (selPoint.value === models.length) {
        swiper_box.value!.style.transition = 'none';
        swiper_box.value!.style.transform = 'translateX(0px)';
        selPoint.value = 0;
        // 为了触发浏览器重新渲染
        setTimeout(() => {
            swiper_box.value!.style.transition = 'transform 1s linear';
        }, 0);
    }
}

let timer: any = null
const animate = (delay = 2000) => {
    timer = setInterval(() => {
        selPoint.value++
        checkPoint(selPoint.value)

    }, delay)
}
const mouseenter = () => {
    clearInterval(timer)
}
const mouseleave = () => {
    animate()
}

onMounted(() => {
    animate()
})

</script>

css

<style scoped>
.container {
    display: flex;
    justify-content: center;
}

.swiper {
    position: relative;
    overflow-x: auto;
    display: flex;
    overflow-y: hidden;
    scrollbar-width: none;
    width: v-bind(imgW);
}

.swiper_box {
    display: flex;
}

.swiper_item {
    width: v-bind(imgW);
    height: 300px;
}

img {
    height: 100%;
}

.pag {
    position: absolute;
    bottom: 20px;
    left: 50%;
    transform: translateX(-50%);
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 10px;
}

.action {
    background-color: red !important;
}

.point {
    width: 10px;
    height: 10px;
    border-radius: 5px;
    background-color: aliceblue;
}

.point:hover {
    cursor: pointer;
}
</style>

source code :

swiper demo