英文:
Swiper/vue useSwiper() doesn't work, empty value undefined
问题
我已创建了我的导航,并希望使用useSwiper
方法来控制按钮,但该方法为空。在沙箱中,我创建了一个完全重复我的代码的示例。正常导航可以工作,但当我想要使用我的按钮时,出现错误。 Sandbox
英文:
I have created my navigation and want to use the useSwiper
method to control the buttons, but the method is empty. In the sandbox, I created an example that completely repeats my code. Normal navigation works, but when I want to use my buttons I get an error. Sandbox
答案1
得分: 0
useSwiper
钩子必须在位于 Swiper 内部的组件中使用。在你的情况下,swiper
是 undefined
。
你可以从 onSwiper
事件中获取 swiper
。 你可以在 codesandbox 中获取更多信息:
<template>
<Swiper
@swiper="onSwiper"
:navigation="true"
:modules="modules"
class="mySwiper"
>
<div>
<button @click.stop="slider.slidePrev()">prev</button>
<button @click.stop="slider.slideNext()">next</button>
</div>
<Swiper-slide>Slide 1</Swiper-slide>
<swiper-slide>Slide 2</swiper-slide><swiper-slide>Slide 3</swiper-slide>
<swiper-slide>Slide 4</swiper-slide><swiper-slide>Slide 5</swiper-slide>
<swiper-slide>Slide 6</swiper-slide><swiper-slide>Slide 7</swiper-slide>
<swiper-slide>Slide 8</swiper-slide><swiper-slide>Slide 9</swiper-slide>
</Swiper>
</template>
<script setup>
import { ref } from "vue";
import "swiper/swiper-bundle.min.css";
import { Navigation } from "swiper";
import { Swiper, SwiperSlide } from "swiper/vue";
const modules = [Navigation];
const slider = ref(null);
const onSwiper = (swiper) => {
slider.value = swiper;
};
</script>
英文:
useSwiper
hook must be used in components which are inside of the Swiper. In your case swiper
is undefined
.
You can get swiper
from onSwiper
event codesandbox:
<template>
<Swiper
@swiper="onSwiper"
:navigation="true"
:modules="modules"
class="mySwiper"
>
<div>
<button @click.stop="slider.slidePrev()">prev</button>
<button @click.stop="slider.slideNext()">next</button>
</div>
<Swiper-slide>Slide 1</Swiper-slide>
<swiper-slide>Slide 2</swiper-slide><swiper-slide>Slide 3</swiper-slide>
<swiper-slide>Slide 4</swiper-slide><swiper-slide>Slide 5</swiper-slide>
<swiper-slide>Slide 6</swiper-slide><swiper-slide>Slide 7</swiper-slide>
<swiper-slide>Slide 8</swiper-slide><swiper-slide>Slide 9</swiper-slide>
</Swiper>
</template>
<script setup>
import { ref } from "vue";
import "swiper/swiper-bundle.min.css";
import { Navigation } from "swiper";
import { Swiper, SwiperSlide } from "swiper/vue";
const modules = [Navigation];
const slider = ref(null);
const onSwiper = (swiper) => {
slider.value = swiper;
};
</script>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论