vue swiper动态获取数据无法滑动问题

简述:

使用swiper插件时,需要通过接口获取图片路径、图片名称等,会出现无法滑动或空白的现象。原因是swiper在获取接口之前初始化,这样渲染的是没获取图片之前的页面。

解决方法一:再用接口调出数据后,初始化swiper

<template>
	<div class="swiper-container">
	    <div class="swiper-wrapper">
	        <div class="swiper-slide" v-for="baseListCon in baseListCon"><img :src="baseListCon" /></div>
	    </div>		    
	    <div class="swiper-button-prev"></div>
	    <div class="swiper-button-next"></div>
	</div>
</template>
<script>
	import Swiper from 'swiper';
	import '../assets/css/swiper.min.css'; 
	export default {
		data() {
			return {
				index: 0,
				baseListCon: "",
			}
		},
		created: function () { 
			
		},
		mounted() { 
			this.getNews(this.index);   //获取swiper图片数据信息
		},
		methods: {
			getNews: function(index) {
				var that = this;
				this.$axios({
      				url: "../../static/base.json",
                	method:'get',
                   	headers:{'Content-Type': 'application/json'}
              	})
				.then((response) => {
				  	if(response.data.status==0) {          
				  		this.baseListCon=response.data.result[index].lists;
				  		that.$nextTick(function() {   // 初始化swiper
					    that.swiper();          
					  })
				  	}
				}, response => {
                    console.log("error"); 
                })
			},
			swiper: function() {        //初始化swiper方法
				var mySwiper = new Swiper(".swiper-container",{ 
					autoplay:true,
		       direction: "horizontal",    
		       loop: true,                
					navigation: {
				      nextEl: '.swiper-button-next',
				      prevEl: '.swiper-button-prev',
				   	} 
		    });
			}
		}
	}
</script>

解决方法二:

<script>
	export default {
		data() {},
		created: function () {},
		mounted() {},
		methods: {
			swiper: function() {        //初始化swiper方法
				var mySwiper = new Swiper(".swiper-container",{ 
					autoplay:true,
		       direction: "horizontal",    
		       loop: true,                
					navigation: {
				      nextEl: '.swiper-button-next',
				      prevEl: '.swiper-button-prev',
				   	},
				   	observeParents:true,   //修改swiper自己或子元素时,自动初始化swiper
                    observer:true,         //修改swiper的父元素时,自动初始化swiper 
		    });
			}
		}
	}
</script>

解决方法三:

<script>
	export default {
		data() {},
		created: function () {},
		mounted() {},
		methods: {
			swiper: function() {        //初始化swiper方法
				var mySwiper = new Swiper(".swiper-container",{ 
					autoplay:true,
		       direction: "horizontal",    
		       loop: true,                
					navigation: {
				      nextEl: '.swiper-button-next',
				      prevEl: '.swiper-button-prev',
				   	} 
		    });
			}
		},
		updated: function() {   
			this.swiper();
		},
	}
</script>

注:本文来自vue中使用swiper插件

你可能感兴趣的:(vue)