Mar*_*ing 1 vue.js nuxt.js vuejs3 swiper.js nuxtjs3
当用户按下箭头键时,我试图调用 swiper 附带的 .slideNext() 和 .slidePrev 。
我已经成功地使用 querySelector 做到了这一点,如下所示:
const changeSlide = (event: KeyboardEvent) => {
const slides = document.querySelector('.swiper').swiper
if(event.key === 'ArrowLeft') {
slides.slidePrev();
} else if (event.key === 'ArrowRight') {
slides.slideNext();
}
}Run Code Online (Sandbox Code Playgroud)
然而,此方法会产生警告,并且该项目通常不允许使用 querySelector。因此,我不想使用 ref 来选择滑动器,但我还没有成功。
这是我尝试过的:
<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue';
import { Navigation } from 'swiper';
import { Swiper, SwiperSlide } from 'swiper/vue';
import 'swiper/css';
import 'swiper/css/navigation';
// just some imports that are needed
const swiperRef = ref();
// swiper as ref
const changeSlide = (event: KeyboardEvent) => {
const slides = swiperRef.value.swiper
// instead of querySelector i use the ref.value
if(event.key === 'ArrowLeft') {
slides.slidePrev();
} else if (event.key === 'ArrowRight') {
slides.slideNext();
}
}
</script>
<template>
<swiper
ref="swiperRef"
:initial-slide="props.initialSlide"
:slides-per-view="1"
:space-between="0"
:modules="[Navigation]"
navigation
>
<swiper-slide> // left out the attributes since they are a mere distraction
<img/> // left out the attributes since they are a mere distraction
</swiper-slide>
</swiper>
</template>Run Code Online (Sandbox Code Playgroud)
从我在源代码中看到的,您无法访问vue 组件上swiper使用的实例,因为它没有公开。refswiper
你还有其他的思考方式:
<swiper>组件的子组件内部,使用该useSwiper()组件。<swiper>组件的父组件上,使用该@swiper事件。swiper一旦安装它就会发送对象:<template>
<swiper @swiper="getRef" />
</template>
<script setup>
const swiper = ref(null)
function getRef (swiperInstance) {
swiper.value = swiperInstance
}
function next () {
swiper.value.slideNext() // should work
}
</script>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3488 次 |
| 最近记录: |