Vue系列——vue2封装swiper轮播组件

69 阅读1分钟

<img :src="item.url"/>

</div>

</div>

</div>

第三步:编写Banner.vue的JavaScript代码。

根据swiper的官方教程,我们需要实例化swiper。

1、导入swiper;

2、导入swiper的css;

3、通过获取图片数据listImg;

4、mounted类似react中的componentDidMount方法,实例化swiper必须等到dom渲染完成才能操作。

<script>

import Swiper from 'swiper';

import 'swiper/dist/css/swiper.min.css';

export default {

data(){

return {

//图片路径

listImg:[

{url:'../../../static/01.jpg'},

{url:'../../../static/02.jpg'},

{url:'../../../static/03.jpg'}

]

}

},

mounted() {

console.log('mounted', this)

var mySwiper = new Swiper ('.swiper-container', {

loop: true,

pagination: {

el: '.swiper-pagination',

},    

// 如果需要前进后退按钮

navigation: {

nextEl: '.swiper-button-next',

prevEl: '.swiper-button-prev',

},

autoplay: {

disableOnInteraction: false,

},

})  

}

}

</script>

第四步:写css样式

<style>

.swiper-container {width: 100%; height: 10rem;}

.swiper-wrapper {width: 100%; height: 100%; }

.swiper-slide { width: 100%;   height: 100%;}

.swiper-pagination-bullet { width:0.833rem;

height: 0.833rem;display: inline-block; background: #7c5e53; }  

.swiper-slide img{width: 100%;height: 100%; }

</style>

.swiper-container {width: 100%; height: 10rem;} .swiper-wrapper {width: 100%; height: 100%; } .swiper-slide { width: 100%; height: 100%;} .swiper-pagination-bullet { width:0.833rem; height: 0.833rem;display: inline-block; background: #7c5e53; } .swiper-slide img{width: 100%;height: 100%; }

完整代码: