有一件事我想在问题上补充,就是关于“eager”。它会始终加载您走马灯中的每张图片,这让我很困扰,因为即使大多数情况下,您只想让它加载与当前图像相邻的图像,但它也会极大地增加流量。
为了实现这个目的(利用@ vue/composition-api),我通常使用这样一个类(它是用typescript编写的,但我想纯JavaScript用户应该也能读懂)
import { reactive, toRef, watch } from '@vue/composition-api';
export class ArrayAdjacentController<T> {
allItems: T[];
availableItems: T[];
currentIndex: number;
constructor(items: T[], placeholder?: T){
this.allItems = items;
this.availableItems = this.allItems.slice(0,2);
this.currentIndex = 0;
if(placeholder){
for(let i=2; i<this.allItems.length; i++)
this.availableItems.push(placeholder);
}
reactive(this);
const currentIndexRef = toRef(this, 'currentIndex');
watch(currentIndexRef, val => {
this.setItem(val);
this.setItem(val-1);
this.setItem(val+1);
});
}
setItem(index:number){
if(this.allItems[index] !== this.availableItems[index])
this.availableItems[index] = this.allItems[index];
}
setCurrent(number:number){
if(number>= this.allItems.length || number < 0)
throw new Error(`ImageDataController: ${number} out of index`);
this.currentIndex = number;
}
}
基本上,它创建了一个数组"availableItems",其中只包含紧挨着当前索引的项目。因此,每次在您的轮播中点击下一个或上一个按钮时,将加载更多的图像。此外,您可以使用占位符来填充数组(我在v-img的情况下使用数据URL和1px x 1px的图像,但如果您想使用分隔符,则只需要这样做,否则它们将不会显示正确的计数)。因此,使用此类,轮播将如下所示。
<v-carousel v-model="internalImages.currentIndex">
<v-carousel-item
v-for="(img, ind) of internalImages.availableItems"
:key="ind"
eager
>
<v-img
:src="img"
eager
/>
</v-carousel-item>
</v-carousel>