如何设置vue可以读取的,对swiper事件处理程序有反应的变量

时间:2019-10-30 02:45:00

标签: javascript vue.js swiper

我正在使用vue-awesome-swiper,我希望能够在特定条件下显示或隐藏“下一个/上一个”按钮。

具体地说,当幻灯片到达开头时,它应该显示NEXT按钮,然后当到达结尾时,它应该隐藏该按钮并显示PREVIOUS按钮。

如果可能,我希望将其设置为v-if可以挂接的变量。我该怎么做?

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;
    }
  }
});

2 个答案:

答案 0 :(得分:1)

您的问题与未定义reachedBeginningreachedEnd变量有关

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

答案 1 :(得分:0)

我发现答案在于将实例绑定到变量。最终代码应如下所示:

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

仍然要感谢糖的指引。