场景:我们需要根据设计图来做一个轮播组件,然后自定义轮播指示点。
官网的轮播组件swiper属性详解:
https://developers.weixin.qq.com/miniprogram/dev/component/swiper.html
前言:
要编写一个自定义组件,首先需要在 json 文件中进行自定义组件声明(将 component 字段设为 true 可这一组文件设为自定义组件)。
一、自定义swiper组件和指示点
1、在components/swiper/swiper.wxml封装组件
<!-- components/swiper/swiper.wxml -->
<!--这是一个普通的轮播-->
<view class="container">
<swiper class="swiper-box" bind:change="swiperChange" interval="4000" circular autoplay>
<block wx:for="{{swiperList}}" wx:key="{{index}}">
<swiper-item>
<image class="targetImg" src="{{item}}" mode="aspectFill"></image>
</swiper-item>
</block>
</swiper>
<!--重置小圆点的样式 -->
<view class="dots">
<view class="dotsBox" style='width:{{(swiperList.length*26+swiperList.length*10) + "rpx"}}'>
<!-- <view class="dotsBox" style='width:180rpx'> -->
<block wx:for="{{swiperList}}" wx:key="{{index}}">
<text class="dot {{index == currentIndex ? 'dot-active' : ''}}"></text>
</block>
</view>
</view>
</view>
2、在components/swiper/swiper.wxss书写组件样式
/* component/swiper/swiper.wxss */
.container {
position: relative;
background: #ffffff;
}
.swiper-box{
width: 750rpx;
height: 560rpx;
}
.targetImg{
width: 100%;
height: 560rpx;
}
/*小圆点 */
.dots{
width: 100%;
height: 4rpx;
display: flex;
position: absolute;
bottom: 30rpx;
}
.dotsBox {
height: 4rpx;
display: flex;
margin: 0 auto;
}
/*未选中时的小圆点样式 */
.dot{
width: 26rpx;
height: 4rpx;
border-radius: 2rpx;
margin-right: 10rpx;
background-color: #ffffff;
opacity: 0.4;
}
/*选中以后的小圆点样式 */
.dot-active{
opacity: 1;
}
3、在components/swiper/swiper.js写组件逻辑代码
Component({
properties: {
swiperList: {
type: Array,
value: [ // 默认数据(可以从引用组件处的属性传入该属性值)
"https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=1352235627,3071480959&fm=15&gp=0.jpg",
"https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=524661168,971104595&fm=26&gp=0.jpg",
"https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=2162464902,1813581798&fm=26&gp=0.jpg",
"https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=2197586356,1203513576&fm=15&gp=0.jpg",
"https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=957308583,1357713210&fm=26&gp=0.jpg"
]
}
},
data: {
currentIndex: 0 // 初始高亮下标
},
methods: {
/* 这里实现控制自定义轮播指示点高亮 */
swiperChange(e) {
this.setData({
currentIndex: e.detail.current
})
}
}
})
二、使用自定义的swiper组件
1、在使用页面的 json 文件中进行引用声明。
// pages/index/index.json
{
"usingComponents": {
"w-swiper":"/components/swiper/swiper"
}
}
2、在页面的 wxml 中就可以像使用基础组件一样使用自定义组件。节点名即自定义组件的标签名,节点属性即传递给组件的属性值。
<!-- pages/index/index.wxml-->
<view class="wrap">
<w-swiper />
</view>
————————————————————————————————————
ps:本示例中的components和pages是在同一级目录。