样式转换过慢,无法转换无限的图像轮播

时间:2020-02-07 17:01:02

标签: javascript vue.js carousel settimeout

我正在研究无限的图像/组件轮播。

我有这样的模板:

<template>
    <div class="simple-carousel-wrapper">
        <div ref="slides-container" 
            v-if="items.length" class="simple-carousel-container" 
            :style="[slidesContainerStyle, useTransition ? slidesContainerStyleTransition : slidesContainerStyleTransitionNone]"
        >
            <div v-if="items.length > 1" class="slide">
                <component :is="items[items.length-1].component" :item="items[items.length-1]"></component>
            </div>
            <div v-for="(item, index) in items" v-bind:key="item.id" class="slide">
                <component :is="item.component" :item="item"></component>
            </div>
            <div v-if="items.length > 1" class="slide">
                <component :is="items[0].component" :item="items[0]"></component>
            </div>
        </div>
    </div>
</template>

我计算出的模板使用属性:

computed: {
    slidesContainerStyle: function(){
        var translateX = -1 * this.tempIndex * 100 + '%';

        var style = {
            transform: 'translate(' + translateX + ')',
        };

        return style;
    },

    slidesContainerStyleTransition: function(){
        var style = {
            transition: 'transform ' + this.transitionDuration + 'ms ease-in',
        };

        return style;
    },

    slidesContainerStyleTransitionNone: function(){
        var style = {
            transition: 'transform 0s',
        };

        return style;
    },

    itemsCount: function(){
        return this.items.length;
    },
},

假设,我们在轮播中有3个项目/图片。为了使轮播无限,我将最后一张图片放在循环之前,将第一张图片放在循环结束时。当我们找到最后一个图像并尝试向前拖动时,我们将转到下一个(第一个克隆的)图像。动画结束时(this.transitionDuration-动画时间),我通过转换为第一张真实图像(未克隆),用真实的第一张图像替换了克隆的第一张图像。我是用以下代码完成的:

setTimeout(() => {
    this.useTransition = false; // this remove transition (transition: 'transform 0s',) from translateX I could set firs or last image without scrolling carousel.

    this.tempIndex = index + 1; // force replacing of my cloned first/last image to real first/last image;

    /*
    this.$nextTick(() => {
        this.useTransition = true;
    });
    */

    setTimeout(() => {
        this.useTransition = true; //move back transition for translateX style

    }, 50);     

    /*
    this.tempIndex = index + 1;

    this.useTransition = true;
    */

}, this.transitionDuration); 

它工作正常,但是如您所见,我使用了它:

setTimeout(() => {
    this.useTransition = true;

}, 50);

这不能保证转换将有时间进行替换。当我只使用这个:

this.useTransition = false;

this.tempIndex = index + 1;

this.useTransition = true;

translateX的转换未替换为transition: 'transform 0s',。如果删除,则最后一行转换成功替换为transition: 'transform 0s',

问题是用50毫秒的延迟替换setTimeout函数的适当方法是什么?

0 个答案:

没有答案