1.安装swiper
npm i --save swiper
2.封装swiper组件,以组件方式在单页面中使用
2.1在components文件夹下,创建swiper文件夹,创建MySwiper.vue页面:
<template>
<div class="swiper">
<div class="swiper-wrapper">
//插槽写法,插入swiper-slider组件
<slot></slot>
</div>
</div>
</template>
<script>
// 1.bundle 引入swiper 所有模块,如果引入默认版本的,没有分页器
import Swiper from 'swiper/bundle'
import 'swiper/css/bundle';
export default {
mounted(){
//2.初始化swiper
new Swiper ('.swiper', {
direction: 'horizontal', // 水平切换选项
loop: true, // 循环模式选项
// 如果需要分页器
pagination: {
el: '.swiper-pagination',
},
autoplay: true,
// 如果需要前进后退按钮
navigation: {
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev',
},
})
},
}
</script>
<style scoped>
.swiper{
height:500px;
}
</style>
2.2在swiper文件夹,创建MySwiperSlider.vue页面:
<template>
<div class="swiper-slide">
//插槽写法:template可以写任意东西
<slot></slot>
</div>
</template>
<script>
export default {
}
</script>
<style scoped>
</style>
3.使用方法
3.1 需求:首页(MyIndex.vue)中需要引入swiper组件
3.2 在MyIndex.vue页面中:
<template>
//3.使用组件
<MySwiperViewVue>
<template #default>
<MySwiperSlider v-for="itemImg,index in imgUrls" :key="index">
<template #default>
<div :style="{'backgroundImage':`url(${itemImg})`}" class="img-box"></div>
</template>
</MySwiperSlider>
</template>
</MySwiperViewVue>
</template>
<script>
//1.引入组件
import MySwiperViewVue from '@/components/swiper/MySwiper.vue'
import MySwiperSlider from '@/components/swiper/MySwiperSlider.vue';
export default {
data(){
return {
//4.图片数据,随便换
imgUrls:[
"https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fsafe-img.xhscdn.com%2Fbw1%2F59616f4c-a9f9-4ba3-9eec-c85ff57f9adb%3FimageView2%2F2%2Fw%2F1080%2Fformat%2Fjpg&refer=http%3A%2F%2Fsafe-img.xhscdn.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1686628880&t=a7031371aabfdb057978f319a0465b79",
"https://pica.zhimg.com/v2-e1d73be07fa6624bfcb4590f690d68d3_1440w.jpg",
"https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fc-ssl.duitang.com%2Fuploads%2Fitem%2F201903%2F15%2F20190315130031_sxkjt.jpeg&refer=http%3A%2F%2Fc-ssl.duitang.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1686629020&t=dd9c3251d08693533af7c4bc3cf6b320"
]
}
},
components:{
//2.注册组件
MySwiperViewVue,MySwiperSlider
}
}
</script>
<style scoped>
.img-box{
width:100%;
height:100%;
background-position: top;
}
</style>