关于Vue中写轮播图的一些需注意的
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Swiper/4.0.2/css/swiper.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/Swiper/4.0.2/js/swiper.js"></script>
<style>
.swiper-container{
width: 600px;
height: 300px;
margin: 10px auto;
}
</style>
</head>
<body>
<div id="app">
<Banner></Banner>
</div>
<template id = "banner">
<div>
<input type="text" v-model = "num">
<div class="swiper-container">
<div class="swiper-wrapper">
<div class="swiper-slide"
v-for = "banner in banners"
:key = "banner.id"
>
{{ banner.text}}
</div>
</div>
<!-- 如果需要分页器 -->
<div class="swiper-pagination"></div>
<!-- 如果需要导航按钮 -->
<div class="swiper-button-prev"></div>
<div class="swiper-button-next"></div>
<!-- 如果需要滚动条 -->
<div class="swiper-scrollbar"></div>
</div>
</div>
</template>
</body>
<script src="https://cdn.bootcss.com/vue/2.6.10/vue.js"></script>
<script>
/*
第三方库的实例化要求,必须真实dom已经存在
业务: 动态数据请求,然后进行第三方库实例化的优化
理由: 将动态数据的第三方库实例化放在updated中是有弊端的,弊端是第三方库会重复实例化(因为动态数据肯定是
会变化的,一变化就会触发updated,那么实例化就会增加一次,会损耗服务器性能)
解决:
1. 加判断条件
在第三方实例化之前加if( this.mySwiper ) return false判断。但这个一写,后面所写的其它条件或者其它实例化
就只能写在if的前面了。
2. 将实例化放到异步队列中去
- 将实例化放在created的数据请求中,然后放在setTimeout中
- vue提供了一个它认为是最好的方案: nextTick
使用: Vue.nextTick this.$nextTick
nextTick表示组件渲染结束之后这个方法才会调用
最优解决方案: nextTick
*/
Vue.component('Banner',{
template: '#banner',
data () {
return {
banners: null,
num:100
}
},
beforeCreate () {
},
created () {
//数据请求一般写在这里
fetch('./data.json')
.then( res => res.json())
.then( data => {
this.banners = data
// setTimeout(()=>{
// this.mySwiper = new Swiper ('.swiper-container', {
// // direction: 'vertical', // 垂直切换选项
// loop: true, // 循环模式选项
// // 如果需要分页器
// pagination: {
// el: '.swiper-pagination',
// },
// // 如果需要前进后退按钮
// navigation: {
// nextEl: '.swiper-button-next',
// prevEl: '.swiper-button-prev',
// },
// // 如果需要滚动条
// scrollbar: {
// el: '.swiper-scrollbar',
// },
// autoplay: true
// })
// },0)
this.$nextTick( () => {
this.swiper = new Swiper('.swiper-container',{
loop: true,
autoplay: true,
pagination: {
el: '.swiper-pagination',
},
// 如果需要前进后退按钮
navigation: {
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev',
},
// 如果需要滚动条
scrollbar: {
el: '.swiper-scrollbar',
}
})
})
})
.catch( error => console.log( error ))
},
beforeMount () {
},
mounted () {
//静态数据的第三方实例化
// 第三库实例化
},
updated () {
console.log( 'updated')
if( this.mySwiper ) return false
}
})
new Vue({
el: '#app'
})
</script>
</html>