创建父组件
<template>
<div id="app">
<van-swipe class="my-swipe" :autoplay="3000" indicator-color="white" :index="2">
<van-swipe-item>
<img src="https://pic.maizuo.com/usr/100004836/9c9cefa41110e8241bae0cbb027b3e48.jpg?x-oss-process=image/quality,Q_70" alt="">
</van-swipe-item>
<van-swipe-item>
<img src="https://pic.maizuo.com/usr/100004836/d841b833dce082d7875a4ea2b8b2516e.jpg?x-oss-process=image/quality,Q_70" alt="">
</van-swipe-item>
<van-swipe-item>
<img src="https://pic.maizuo.com/usr/100004836/d841fc6791d7336fb3febc32d6980f40.jpg?x-oss-process=image/quality,Q_70" alt="">
</van-swipe-item>
</van-swipe>
</div>
</template>
<script>
import Swipe from './components/van-swipe'
import SwipeItem from './components/van-swipe-item'
export default {
components: {
Box,
'van-swipe': Swipe,
'van-swipe-item': SwipeItem
},
mounted(){
console.log(this.$children);
}
}
</script>
<style>
img{
width: 100%;
}
</style>
创建第一个子组件van-swipe
防止页面中多个地方需要用swipe,所以这里用this.$refs.swiper替换获取DOM
<template>
<div class="van-swipe swiper-container" ref="swiper">
<div class="swiper-wrapper">
<slot/>
</div>
<pagination :value="activeIndex" @input="inputAction" :length="length"/>
</div>
</template>
<script>
import pagination from './van-swipe-pagination'
export default {
components: {
pagination
},
props: {
autoplay: Number,
index: Number
},
data(){
return {
activeIndex: this.index,
length: 0
}
},
mounted(){
this.length = this.$children.length - 1;
this.mySwiper = new Swiper(this.$refs.swiper, {
// loop: true,
autoplay: this.autoplay,
initialSlide: this.index,
onSlideChangeEnd: (swiper)=>{
this.activeIndex = swiper.realIndex;
}
});
},
methods: {
inputAction(index){
this.activeIndex = index;
console.log(index);
this.mySwiper && this.mySwiper.slideTo(index, 200);
}
}
}
</script>
<style>
.pagination{
width: 100%;
height: 10px;
background: red;
position: absolute;
bottom: 10px;
left: 0;
z-index: 10;
display: flex;
align-items: center;
justify-content: center;
}
.pagination-item{
width: 8px;
height: 8px;
background: white;
border-radius: 4px;
margin: 0 4px;
}
.pagination-item.active{
background: blue;
}
</style>
创建第二个子组件van-swipe-item
<template>
<div class="van-swipe-item swiper-slide">
<slot/>
</div>
</template>
创建第三个子组件pagination
<template>
<!-- 自定义实现pagination -->
<nav class="pagination">
<li class="pagination-item"
v-for="(item, index) in length" :key="item"
:class="{active: value===index}"
@click="changeAction(index)">
</li>
</nav>
</template>
<script>
export default {
props: {
value: Number,
length: Number
},
methods: {
changeAction(index){
this.$emit('input', index);
}
}
}
</script>