Artvader
Artvader

Reputation: 958

How to set a variable that vue can read that reacts to swiper's event handlers

I'm using vue-awesome-swiper and I want to be able to show or hide the Next/Previous buttons on specific conditions.

Specifically, when the slide has reached the beginning, it should show the NEXT button, then when it reaches the end, it should hide that button and show the PREVIOUS button instead.

If possible, I would want it to be set as a variable that v-if can hook on. How do I go about doing that?

HTML

   <div id="swiper">
<div class="menu-tabs-icon-label">
    <swiper ref="productMenu" :options="swiperNavMenu">
        <swiper-slide>
            <div class="nav-item">
                <a href="#"> Item 1 </a>
            </div>
        </swiper-slide>
        <swiper-slide>
            <div class="nav-item">
                <a href="#"> Item 2 </a>
            </div>
        </swiper-slide>
        <swiper-slide>
            <div class="nav-item ">
                <a href="#"> Item 3 </a>
            </div>
        </swiper-slide>
    <div v-if="reachedEnd" class="swiper-button-prev" slot="button-prev"></div>
    <div v-if="reachedBeginning" class="swiper-button-next" slot="button-next"></div> 
    </swiper>
    </div>
</div>

JS

  new Vue({
  el: "#swiper",
  components: {
    LocalSwiper: VueAwesomeSwiper.swiper,
    LocalSlide: VueAwesomeSwiper.swiperSlide
  },
  data: {
    swiperNavMenu: {
      freeMode: true,
      slidesPerView: 5.75,
      on: {
        reachBeginning: function() {
          reachedBeginning = true; 
        },
        reachEnd: function() {
          reachedEnd = true;
        }
      }
    }
  },
  computed: {
    swiperA() {
      return this.$refs.productMenu.swiper;
    }
  }
});

Upvotes: 0

Views: 1246

Answers (2)

Artvader
Artvader

Reputation: 958

I found that the answer lies in binding the instance to the variable. The final code should look like this:

data() {
const self = this; // this is the line that fixes it all
return { 
  reachedEnd: false,
  swiperNavMenu: {
    on: {
      reachEnd: function(){
        self.reachedEnd=true
      }
    }
  }
 };
},

Still thanks to sugars for pointing the way.

Upvotes: 0

sugars
sugars

Reputation: 1493

Your problem is related that reachedBeginning and reachedEnd variables are not defined

...
data() {
  return {
    reachedBeginning: false,
    reachedEnd: false,
    swiperNavMenu: {
      freeMode: true,
      slidesPerView: 5.75,
      on: {
        reachBeginning: ()=> {
          this.reachedBeginning = true; 
        },
        reachEnd: ()=> {
          this.reachedEnd = true;
        }
      }
    }
  }  
},
...

Upvotes: 1

Related Questions