关于swiper动态更改,无法更新的悖论

2018/03/06 15:48
阅读数 1.2K

关于swiper动态更改,无法更新的悖论

<p> 以前都觉得swiper的使用很简单,那是因为使用swiper时都是写的数据,按照官网上介绍直接初始化swiper,随便丢一个地方初始化就ok了,但是在很多需求中,我们都需要动态的改变数据,这样可能就会遇到很多问题。</p>

<p> 最近在react搭建环境中,使用swiper就遇上一些问题:</p>

<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'] }

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

}

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

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

 

<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>
展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部