關於swiper動態更改,沒法更新的悖論

關於swiper動態更改,沒法更新的悖論

<p> 之前都以爲swiper的使用很簡單,那是由於使用swiper時都是寫的數據,按照官網上介紹直接初始化swiper,隨便丟一個地方初始化就ok了,可是在不少需求中,咱們都須要動態的改變數據,這樣可能就會遇到不少問題。</p>react

<p> 最近在react搭建環境中,使用swiper就趕上一些問題:</p>app

<p> 1. 初始化後,在react的鉤子裏面new 出來的swiper對象做用域問題。<br/> 2. 更改swiper,更新時不少方法不能使用。<br/> 3. 修改數據swiper裏面的slider出現混亂。<br/> 4. 數據不匹配(須要加載的數據以改變,可是swiper裏面的數據出現錯誤)。<br/> </p> ``` class Banner extends Component { static defaultProps = { imageData:['image/b1.jpg','image/b2.jpg','image/b3.jpg','image/b4.jpg','image/b5.jpg','image/b6.jpg','image/b7.jpg','image/b8.jpg'], imgData:['img/1.jpg','img/2.jpg','img/3.jpg','img/4.jpg','img/5.jpg','img/6.jpg','img/7.jpg','img/8.jpg','img/9.jpg','img/10.jpg','img/11.jpg'] }ide

componentDidMount() {
	this.mySwiper = new Swiper('.Banner', {
      pagination: {
        el: '.swiper-pagination',
      },
      autoplay: {
      	delay: 3000,
	    stopOnLastSlide: false,
	    disableOnInteraction: true,
      },
      loop:true,
      effect : 'fade',
    });
}

componentWillReceiveProps() {
	console.log(1111);
	this.mySwiper.update();
}

render() {
	var sliderFn = (arr) => {
		var sliderArr = [];
		for(var i=0; i<arr.length; i++) {
			sliderArr.push(<div class="swiper-slide"><img src={arr[i]}/>'</div>)
		}
		return sliderArr;
	}
	
	return (
		<div class="swiper-container Banner">
		    <div class="swiper-wrapper">
		    	{sliderFn(this.props.imgFlag ? this.props.imgData : this.props.imageData)}
		    </div>
		    <div class="swiper-pagination"></div>
		</div>
	)
}

}oop

<p>
真正的核心部分在
</p>
<p>
observer:true,//修改swiper本身或子元素時,自動初始化swiper </p>
<p>observeParents:false,//修改swiper的父元素時,自動初始化swiper </p>

onSlideChangeEnd: function(swiper){    swiper.update();
   mySwiper.startAutoplay();    mySwiper.reLoop();
}this

<p>加上這串代碼後,使用基本正常</p>

<p>mySwiper.reLoop(); 從新對須要循環的slide個數進行計算,當你改變了slidesPerView參數時須要用到,須要自動輪播的時候必需要加上;</p>

<p>swiper.update();  更新Swiper,這個方法包含了updateContainerSize,updateSlidesSize,updateProgress,updatePagination,updateClasses方法。也就是數據改變是從新初始化一次swiper;</p>

<p>mySwiper.startAutoplay(); 從新開始自動切換;</p>

<p>可是還會有一個問題,好比說在初始化頁面是,初始化加載一組數據,可是這組數據裏面只有一條信息,可是其餘組數據裏面包含了多條信息,在這種狀況下必需要手動切換一次才能觸發自動輪播,還沒找到解決辦法。</p>

<p>
以上就是遇到的一些問題,記錄一下,之後遇到還能夠看看。
</p>
相關文章
相關標籤/搜索