2

如何根据我的逻辑取消单击 swiper 中的下一个按钮?

我在基于swiperjs 的 vue 中使用swiperjs,并且我想阻止用户根据我的逻辑函数的结果滑动或单击按钮转到下一张幻灯片。

我试试这个 - 不起作用。

 swiper.on('init', async () => {

    swiper.navigation.$nextEl.on('click', (e) => {
      if (true /* mylogic() */) { e.preventDefault(); }
    });
    ...
 });

和这个:

  <div @click="onNext" slot="button-next"></div>
  ...
  function onNext(e) {
   if (true /* mylogic() */) { e.preventDefault(); }
  }

没有任何效果 - 刷卡器仍然移动到下一张幻灯片。

如何防止点击移动到下一张幻灯片?

Codesandbox.io 上的代码

4

1 回答 1

0

通过将滑动选项配置为使用 .swiper-button-prev 来触发下一次滑动,它发生在您的点击函数 onNext() 之前。

本质上,您需要防止在下一个箭头单击时触发 swiper,然后使用 swiper.slideNext() 方法自己实现它。

所以。将 ref 添加到 swiper 元素,删除 swiper-button-prev 类,将 onNext() 方法移动到方法对象(它应该在哪里,对吗?),在你的函数中调用 swiper.slideNext() 方法,如果someCondition 为真。

密码箱...

<template>
  <div id="app">
    <h2>1</h2>
    <swiper ref="mySwiper" :options="swiperOption1">
      <swiper-slide v-for="(game, index) in jackpotGames" v-bind:key="index">
        <div class="game-item game-item__1">
          game_id: {{game.game_id}},
          <br>
          provider: {{game.provider}},
          <br>
          img: {{game.img}}
        </div>
      </swiper-slide>
      <div class="swiper-button-prev" slot="button-prev">←&lt;/div>
      <div @click="onNext" class="" slot="button-next">→&lt;/div>
      <div class="swiper-pagination" slot="pagination"></div>
    </swiper>
  </div>
</template>

<script>
import { swiper, swiperSlide } from "vue-awesome-swiper";

export default {
  name: "App",
  components: {
    swiper,
    swiperSlide
  },

  data() {
    return {
      swiperOption1: {
        slidesPerView: 4,
        slidesPerColumn: 1,
        spaceBetween: 16,
        freeMode: true,
        pagination: {
          el: ".swiper-pagination",
          type: "progressbar"
        },
        navigation: {
          // nextEl: ".swiper-button-next",
          prevEl: ".swiper-button-prev"
        },
        breakpoints: {
          640: {
            slidesPerView: 2,
            spaceBetween: 8,
            pagination: {
              el: ".swiper-pagination",
              type: "bullets"
            },
            navigation: {}
          }
        }
      },

      jackpotGames: [
        // Removed to save space in this answer.
      ]
    };
  },
  methods: {
    onNext(e) {
      let someCondition = true;
      if (someCondition) {
        this.swiper.slideNext();
      }
    }
  },
  computed: {
    swiper() {
      return this.$refs.mySwiper.swiper
    }
  },
  mounted() {
    console.log('swiper', this.swiper);
  }
};
</script>
于 2020-05-23T13:49:42.310 回答