vue使用swiper循环模式下,使用click事件,怎么获取其中的dom数据?

绝恋
  • 153

在vue中使用swiper,使用内置的onclick方法,但是这个onclick中this指向的是swiper,要怎么才能获取到其中的dom数据呢?

html

 <swiper :options="swiperOption" ref="mySwiper" v-if="bannerList.length">  <!-- 先加载数据否则swiper循环轮播失效 -->
    <swiper-slide v-for="(item,index) in bannerList" :key="index">
        <div class="banner-img"  
        :style="{backgroundImage: 'url(' + item.img + '?x-oss-process=image/resize,w_400)', 
        backgroundSize:'cover',backgroundPosition:'50% 50%'}">
        </div>   
    </swiper-slide>
    <div class="swiper-pagination" slot="pagination"></div>
</swiper>

Js

  data(){
        return{
            swiperOption: {
                speed:500,
                autoplay: {
                    disableOnInteraction: false,
                    delay: 3000,
                    },
                loop: true,
                centeredSlides:true,
                loopAdditionalSlides: 100,
                observer:true,
                pagination: {
                    el: '.swiper-pagination'       
                },
                effect: 'coverflow', 
                coverflowEffect: {
                    rotate: 0,
                    stretch: 10,
                    depth: 150,
                    modifier: 2,
                    slideShadows: false
                },
                 on:{
                    click: function(e){
                       console.log(e)
                    },
                },
            },
        }
    },

我想点击swiper然后跳转到对应的链接,怎么才能获取到?

回复
阅读 4k
4 个回答

可以添加ref属性来实现

在外部定义一个当前 Vue 的实例,如 vm,然后再利用楼上说的 ref 属性来获取。

已解决,首先

let vm = null;

然后添加

 computed: {
      swiper() {
        return this.$refs.mySwiper.swiper
      }
    },
     created() {
        vm = this;
    },

在 methods中定义方法

   handleClickSlide(index) {
        window.location.href = this.bannerList[index].url 
   }, 

最后在swiper中的click定义即可,就可以跳转到对应的Url

 on:{
    click: function(){
        vm.handleClickSlide(this.realIndex);
      },
   }
boi5y6k
  • 2
新手上路,请多包涵
import { Swiper, SwiperSlide } from "vue-awesome-swiper";
import { AMapManager } from "vue-amap";
import "swiper/dist/css/swiper.css";
let vm = null;
export default {
  name: "resourceSearch",
  components: {
    Swiper,
    SwiperSlide,
    AMapManager,
  },
  data() {
    return {
      toolbarOption: {
        direction: "vertical",
        slidesPerView: 2,
        preventClicks: false,

        navigation: {
          nextEl: ".mrt-arr.down",
          prevEl: ".mrt-arr.up",
        },
        on: {
          click() {
            const realIndex = this.clickedIndex;

            vm.swiperClick(realIndex);
          },
        },
      },
宣传栏