vue接收索引_vue-awesome-swiper获取当前页的索引

首说一下思路: 从swiper的dom元素中获取当前页的索引, 只要拿到当前页的索引就可以获取对应的数据做事情了. 一共两步

步骤1: 在script中获取并保存swiper的索引

const c_swiper = document.getElementsByClassName("swiper")

步骤2: 在swiper滚动事件里从swiper的dom元素中取当前的页码.有需要也可以在其他事件中获取

swiperOptions: {

...

on: {

slideChange:() => {console.log("轮播图滚动事件 --->",c_swiper[0].swiper.activeIndex)}

}

}

下面是完整代码(看注释)

import { Swiper, SwiperSlide, directive } from vue-awesome-swiper

// 1. 存储swiper元素,避免重复获取

const c_swiper = document.getElementsByClassName("swiper")

export default {

data() {

return {

imgs:["/static/images/temp_img_01.jpg","/static/images/temp_img_02.jpg"],

swiperOptions: {

pagination: {

el: .swiper-pagination,

},

autoplay: {

delay:5000,

stopOnLastSlide:false,

disableOnInteraction:false

},

on: {

// 2. 在滚动事件中通过上面保存的swiper元素获取当前页索引,可以打印一下c_swiper看一下内部属性

slideChange:() => {console.log("轮播图滚动事件 --->",c_swiper[0].swiper.activeIndex)}

}

},

}

}

}

首说一下思路: 从swiper的dom元素中获取当前页的索引, 只要拿到当前页的索引就可以获取对应的数据做事情了. 一共两步 步骤1: 在script中获取并保存swiper的索引 const c_swiper = document.getElementsByClassName("swiper") 步骤2: 在swiper滚动事件里从swiper的dom元素中取当前的页码.有需要也可以在其他事件中获取 swiperOptions: { ... on: { slideChange:() => {console.log("轮播图滚动事件 --->",c_swiper[0].swiper.activeIndex)} } } 下面是完整代码(看注释) import { Swiper, SwiperSlide, directive } from vue-awesome-swiper // 1. 存储swiper元素,避免重复获取 const c_swiper = document.getElementsByClassName("swiper") export default { data() { return { imgs:["/static/images/temp_img_01.jpg","/static/images/temp_img_02.jpg"], swiperOptions: { pagination: { el: .swiper-pagination, }, autoplay: { delay:5000, stopOnLastSlide:false, disableOnInteraction:false }, on: { // 2. 在滚动事件中通过上面保存的swiper元素获取当前页索引,可以打印一下c_swiper看一下内部属性 slideChange:() => {console.log("轮播图滚动事件 --->",c_swiper[0].swiper.activeIndex)} } }, } } }
经验分享 程序员 微信小程序 职场和发展