如何在 Vue3.0 中使用 Swiper slideTo()?

luz*_*ian 1 swiper vue.js vuejs3 swiperjs

Vue 版本:3.0.2

刷卡版本:6.3.5

我想在Vue3.0中使用Swiper的slideTo方法,但是好像不行。

你能告诉我怎么用吗?https://codesandbox.io/s/interesting-hooks-1jblc?file=/src/App.vue

Yom*_* S. 5

您似乎正在使用一个库,但参考另一个库来获取文档。

您正在从 导入库swiper/vue,因此它必须是官方库;在这种情况下,访问 Swiper 实例略有不同:您需要存储 Swiper 实例。(请参阅控制器模式)。所以在你的情况下:

<template>
  <swiper
    style="border: 1px solid red; width: 400px"
    :slides-per-view="1"
    @swiper="onSwiper"
  >
    <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>

  <button @click="handleSlideTo">slide to 4</button>
</template>

<script>
import { Swiper, SwiperSlide } from "swiper/vue";
import "swiper/swiper-bundle.css";

export default {
  name: "App",
  
  components: {
    Swiper,
    SwiperSlide,
  },

  data() {
    return {
      swiper: null,
    };
  },

  methods: {
    onSwiper(swiper) {
      this.swiper = swiper;
    },

    handleSlideTo() {
      this.swiper.slideTo(3);
    },
  },
};
</script>
Run Code Online (Sandbox Code Playgroud)

不要与其他库 ( )的使用ref混淆vue-awesome-swiper


小智 5

如果您正在使用<script setup>,您可以这样做:

<script setup>
  import { ref } from 'vue'
  import { Swiper, SwiperSlide } from 'swiper/vue'

  import 'swiper/css'

  const swiperInstance = ref()

  function onSwiper(swiper) {
    swiperInstance.value = swiper
  }

  function goToSlide(position) {
    swiperInstance?.slideTo(position)
  }
</script>

<template>
  <button @click="goToSlide(3)">
    Go to slide 3
  </button>

  <Swiper @swiper="onSwiper">
    <SwiperSlide v-for="i in 4">
      Slide {{ i }}
    </SwiperSlide>
  </Swiper>
</template>
Run Code Online (Sandbox Code Playgroud)