swiper是微信小程序的一個滑動組件,非常重要。如果只是做簡單的輪播圖而不進行復雜的邏輯,直接可以使用,甚至不需要知道組件的方法。
今天在做一個如下的頁面時,快速滑動(dong)swiper出現了問(wen)題:
控制臺(tai)打印,發現bindChange綁定的方法重復執行了,我(wo)們再看(kan)官方文(wen)檔的解釋(shi):
//developers.weixin.qq.com/miniprogram/dev/component/swiper.html

而我(wo)們(men)的bindChange確實(shi)使用(yong)了setData(),來保(bao)證(zheng)swiper組件(jian)的current屬性與我(wo)們(men)的this.data.index同步。為什(shen)么要有(you)this.data.index這(zhe)個(ge)變量(liang)?是(shi)因為我(wo)們(men)要獲得當前的頁數進行其他的操作。比如(ru)上圖底部的slider就用(yong)到這(zhe)個(ge)變量(liang)。但(dan)是(shi)這(zhe)個(ge)變量(liang)必(bi)須在bindChange進行同步。
至(zhi)此(ci)(ci),我們的(de)(de)程(cheng)序在(zai)快速(su)滑動的(de)(de)時候是有問題的(de)(de)。不斷觸發setData()。此(ci)(ci)外,在(zai)官(guan)方的(de)(de)開(kai)發社區找到這么一條:

后來一想,在(zai)bindChange改變swiper的current是有(you)問題的,那么,改變另(ling)外的變量呢?答案是沒(mei)有(you)問題的。
那么,我們的做(zuo)法是(shi),data里定(ding)義2個變量:
data{
cur:0,//改變當前索引
index: 0//當前的索引
}
當(dang)前的頁(ye)數(shu)用index來(lai)標記。swiper組(zu)件的current屬性(xing)我(wo)們用變量cur。互(hu)不(bu)干擾。當(dang)頁(ye)面變化時(shi),我(wo)們設(she)置(zhi)index,當(dang)我(wo)們需(xu)要(yao)改變頁(ye)面時(shi),我(wo)們設(she)置(zhi)cur.index和(he)cur是(shi)不(bu)同步的。
<swiper
autoplay="{{autoplay}}"
interval="{{interval}}"
duration="{{duration}}"
bindchange="swiperChange"
current="{{cur}}">
swiperChange(e){
let current = e.detail.current;
let source = e.detail.source
//console.log(source);
console.log(current,this.data.index,this.data.cur)
this.setData({
index:current
})
這(zhe)個問(wen)題的出路就是,不要想著(zhu)用(yong)一個變(bian)量(liang)作為swiper的current和當前頁碼的標(biao)記。一旦分開(kai)這(zhe)2個變(bian)量(liang),問(wen)題就解(jie)決了。