解决swiper初始化过早问题有以下方法:
(1)组件法:
- 给组件加“ : key=状态.length”;
- 给组价加:“ v-if=‘状态.length’ ”;
- 在组件mounted生命周期函数里进行初始化;
(2)指令法:
- inserted生命周期函数里进行初始化;
(3)this.$nextTick法:在生命周期函数updated后面执行,且只执行一次,当状态再更新就不会执行了,所以进行swiper初始化非常合适,解决了在updated里会多次初始化的问题:
写法:
this.$nextTick(() => {
console.log("我比updated执行的都晚,而且只执行一次")
new Swiper(".swiper", {
// direction: 'vertical', // 垂直切换选项
loop: true, // 循环模式选项
// 如果需要分页器
pagination: {
el: '.swiper-pagination',
}
})
})
完整代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="./swiper/swiper-bundle.min.css">
<script src="./swiper/swiper-bundle.min.js"></script>
<script src="./lib/vue.js"></script>
<style>
/* .swiper {
width: 600px;
height: 300px;
background-color: yellow;
} */
</style>
</head>
<body>
<div id="box">
<header>导航</header>
<div class="swiper">
<div class="swiper-wrapper">
<!-- <div class="swiper-slide">11111</div>
<div class="swiper-slide">22222</div>
<div class="swiper-slide">33333</div> -->
<div class="swiper-slide" v-for="data in datalist" :key="data">
<img :src="data" alt="">
</div>
</div>
<!-- 如果需要分页器 -->
<div class="swiper-pagination"></div>
</div>
<footer>底部内容</footer>
</div>
<script>
new Vue({
el: "#box",
data: {
datalist: []
},
mounted() {
//ajax请求回来的数据
setTimeout(() => {
//后端的返回的数据用数组接收
this.datalist = ["https://static.maizuo.com/pc/v5/usr/movie/e856bdc65507b99800f22e47801fa781.jpg",
"https://p0.pipi.cn/mmdb/25bfd6ddb53c7e5015d23c5bc24d876c03d41.jpg?imageView2/1/w/160/h/220",
"https://p0.pipi.cn/mmdb/25bfd692ddd7e13139313954ee2938728ad6a.jpg?imageView2/1/w/160/h/220"]
this.$nextTick(() => {
console.log("我比updated执行的都晚,而且只执行一次")
new Swiper(".swiper", {
// direction: 'vertical', // 垂直切换选项
loop: true, // 循环模式选项
// 如果需要分页器
pagination: {
el: '.swiper-pagination',
}
})
})
}, 2000)
},
// updated(){
// new Swiper(".swiper", {
// // direction: 'vertical', // 垂直切换选项
// loop: true, // 循环模式选项
// // 如果需要分页器
// pagination: {
// el: '.swiper-pagination',
// }
// })
// }
})
</script>
</body>
</html>
结果:
缺点是:没有复用性