虽然以上答案是正确的,但在更新数组后需要显示带有更新/新数据的新幻灯片,并且需要刷新slick滑块实例时,还有一个问题。
如果我们不这样做,那么不论数组是否已经更新,slick都会继续显示之前绑定的旧数据。
因此,使用现代框架和ES6方法的代码可能如下所示。
假设我们正在通过循环在vue、react、angular或alpine js等现代库中显示数据数组,并且我们有一个名为
shops
的数组要作为滑块显示。
每当有人触发某个操作时,数组(和最终的DOM)都会被更新,但我们必须手动告诉slick滑块根据新数组中的数据更新幻灯片数据。这里的数据以
shops
数组的形式存在。
{
shops: [],
init() {
let self = this;
self.$watch('shops',(currentShops,oldShops) => {
$('#shops-section-slider.slick-initialized').slick('slickRemove', null, null, true);
currentShops.forEach(function(shop,index) {
$('#shops-section-slider.slick-initialized').slick('slickAdd', self.getSliderTmpl(shop));
})
$('#shops-section-slider.slick-initialized').slick('refresh');
})
shopsPromise.then(function(data) {
shops.push(data)
}).then(function() {
$('#shops-section-slider').not('.slick-initialized').slick({
})
});
},
getSliderTmpl(shop) {
return `<div class="col-12 col-md-6 col-lg-4 col-xl-4 d-flex flex-column shops-section">
<div class="row flex-grow-1 flex-column flex-xxl-row">
<div class="col-12 col-xxl-6">
<div class="shops-img position-relative">
<strong class="shops-title-card d-block d-xxl-none">${shop.whateveravailable}</strong>
</div>
</div>
</div>
</div>`;
}
}
在HTML中,我们甚至不需要
<template>
元素,它在alpine js中用作循环,因为它会创建错误的宽度和问题,由于有一个额外的幻灯片,所以我们可以省略它,从而仅通过js来管理整个幻灯片数据和模板。
<div class="row shops-section-wrapper" id="shops-section-slider"></div>