【組件庫】自定義swiper組件
效果展示

組件設(shè)置
步驟1
在pages目錄下,新建文件夾components
步驟2
在components下建立新文件夾swiper
在swiper目錄下,新建4個(gè)文件,分別為
swiper.js swiper.json swiper.wxml swiper.wxss
各文件位置示意圖如下:

?注:此時(shí)編譯會報(bào)錯(cuò) 錯(cuò)誤顯示在json那里 先不用管 后面把代碼復(fù)制粘貼上去再編譯就好了
步驟3
分別把下面代碼復(fù)制進(jìn)swiper目錄中的四個(gè)文件
swiper.js
Component({
/**
* 組件的屬性列表
*/
properties: {
imgUrls: Array,
},
/**
* 組件的初始數(shù)據(jù)
*/
data: {
currentIndex: 0
},
/**
* 組件的方法列表
*/
methods: {
swiperChange(e) {
this.setData({
currentIndex: e.detail.current
});
}
}
});
swiper.json
{
"component": true,
"usingComponents": {}
}
swiper.wxml
<swiper indicator-dots="false" autoplay="{{true}}" interval="2000" indicator-dots="{{false}}" indicator-color='#8a8a8a'
indicator-active-color='#333' circular="true" class="swiper-block" bindchange="swiperChange" previous-margin="100rpx"
next-margin="100rpx" current="{{0}}">
<block wx:for="{{imgUrls}}" wx:index="{{index}}" wx:key="{{index}}">
<swiper-item class="swiper-item ">
<image mode="aspectFill" src="{{item}}" class="slide-image {{currentIndex == index ? 'active' : 'common'}}" />
</swiper-item>
</block>
</swiper>
swiper.wxss
page {
background-color: #fff;
}
.swiper-block {
background: #fff;
height: 500rpx;
width: 100%;
}
.swiper-item {
display: flex;
flex-direction: column;
justify-content: start;
align-items: flex-start;
overflow: unset;
width: 550rpx;
height: 450rpx;
padding-top: 70rpx;
padding-bottom: 20rpx;
box-sizing: border-box;
}
.slide-image {
height: 300rpx;
width: 450rpx;
border-radius: 10rpx;
margin: 0rpx 50rpx;
z-index: 1;
box-shadow: 10rpx 5px 40rpx rgba(0, 0, 0, 0.5);
}
.active {
transform: scale(1.3);
transition: all .5s ease-in 0s;
z-index: 20;
opacity: 1;
}
.common {
transform: scale(1);
transition: all .5s ease-in 0s;
z-index: 0;
opacity: 0.4;
}
.dots-box {
display: flex;
justify-content: center;
align-items: center;
}
使用組件
步驟1
在需要使用swiper組件的頁面的json文件中引入組件
{
"usingComponents": {
"custom-swiper": "../components/swiper/swiper"
}
}
?注意:../components/swiper/swiper表示組件的位置 這里根據(jù)自己實(shí)際設(shè)置的位置關(guān)系進(jìn)行替換即可
步驟2
在頁面的wxml頁面中,使用組件代碼
<custom-swiper imgUrls="{{carouselImgUrls}}" />
carouselImgUrls
類型:數(shù)組 作用:用于存儲輪播圖圖片的地址(網(wǎng)絡(luò)地址 or 本地地址)
步驟3
在頁面的js文件的data中,添加carouselImgUrls變量
data: {
carouselImgUrls: [
/*
圖片的個(gè)數(shù)自定義
圖片來源:圍脖
作者:少女兔iiilass
侵刪
*/
"https://wx1.sinaimg.cn/mw2000/7f97a73fly1gsgixv69f6j20j60j60ui.jpg",
"https://wx1.sinaimg.cn/mw2000/7f97a73fly1gsgixvage4j20j60j6tah.jpg",
"https://wx1.sinaimg.cn/mw2000/7f97a73fly1gsgixvadfnj20j60j60uk.jpg",
"https://wx1.sinaimg.cn/mw2000/7f97a73fly1gsgixvdcswj20j60j6jt6.jpg",
"https://wx1.sinaimg.cn/mw2000/7f97a73fly1gsgixv6kmbj20j60j6dhg.jpg"
],
},
最后只需要編譯代碼 就可以得到效果圖了

結(jié)語
注:測試圖片來源網(wǎng)絡(luò),侵刪
創(chuàng)作不易
如果您覺得寫的不錯(cuò)的話
點(diǎn)贊+在看+收藏 ??
評論
圖片
表情
