如何使用滑动器内的功能参考



我试图在滑动器幻灯片中使用函数ref,但得到了重复的结果。

<swiper-slide>
<first-step :ref="(el) => { steps.push(el)}" />
</swiper-slide> 
<swiper-slide>
<second-step :ref="(el) => { steps.push(el)}" />
</swiper-slide>
setup(){
const steps = ref([]);
return { steps}
}

正如Vue文档中提到的,当使用函数refs时,每次更新组件时都会调用绑定函数。并且组件在其生命周期中被多次更新,这就是为什么一些els被复制的原因。

为了防止重复,我认为应该创建多个refs实例,并像这样通过computed将它们组合在一起。

<swiper-slide>
<first-step ref="firstStepRef" />
</swiper-slide> 
<swiper-slide>
<second-step ref="secondStepRef" />
</swiper-slide>
setup(){
const firstStepRef = ref(null);
const secondStepRef = ref(null);
function getEl(elRef) {
if (!elRef.value) return null;
return elRef.value.$el;
)
const steps = computed(() => {
return [getEl(firstStepRef), getEl(secondStepRef)];
}
return { steps}
}

ps: above code is not well-tested yet.

最新更新