項目目錄:

步驟一:創建組件
聲明這一組文件為自定義組件
stepper.json
{
"component": true,
"usingComponents": {}
}
步驟二:編寫組件代碼
1.邏輯層
stepper.js
// component/stepper/stepper.js
Component({
properties: {
//
},
data: {
// 這里是一些組件內部數據
// input默認是1
num: 1,
// 使用data數據對象設置樣式名
minusStatus: 'disabled'
},
methods: {
// 這里放置自定義方法
/* 點擊減號 */
bindMinus: function () {
var num = this.data.num;
// 如果大於1時,才可以減
if (num > 1) {
num--;
}
// 只有大於一件的時候,才能normal狀態,否則disable狀態
var minusStatus = num <= 1 ? 'disabled' : 'normal';
// 將數值與狀態寫回
this.setData({
num: num,
minusStatus: minusStatus
});
},
/* 點擊加號 */
bindPlus: function () {
var num = this.data.num;
// 不作過多考慮自增1
num++;
// 只有大於一件的時候,才能normal狀態,否則disable狀態
var minusStatus = num < 1 ? 'disabled' : 'normal';
// 將數值與狀態寫回
this.setData({
num: num,
minusStatus: minusStatus
});
},
/* 輸入框事件 */
bindManual: function (e) {
var num = e.detail.value;
// 將數值與狀態寫回
this.setData({
num: num
});
}
}
})
2.頁面布局
stepper.wxml
<!--component/stepper/stepper.wxml-->
<!-- 主容器 -->
<view class="stepper">
<!-- 減號 -->
<text class="{{minusStatus}}" bindtap="bindMinus">-</text>
<!-- 數值 -->
<input type="number" bindchange="bindManual" value="{{num}}" />
<!-- 加號 -->
<text class="normal" bindtap="bindPlus">+</text>
</view>
3.樣式
stepper.wxss
/* component/stepper/stepper.wxss */
/*全局樣式*/
page {
padding: 20px 0;
}
/*主容器*/
.stepper {
width: 80px;
height: 26px;
/*給主容器設一個邊框*/
border: 1px solid #ccc;
border-radius: 3px;
margin:0 auto;
}
/*加號和減號*/
.stepper text {
width: 19px;
line-height: 26px;
text-align: center;
float: left;
}
/*數值*/
.stepper input {
width: 40px;
height: 26px;
float: left;
margin: 0 auto;
text-align: center;
font-size: 12px;
/*給中間的input設置左右邊框即可*/
border-left: 1px solid #ccc;
border-right: 1px solid #ccc;
}
/*普通樣式*/
.stepper .normal{
color: black;
}
/*禁用樣式*/
.stepper .disabled{
color: #ccc;
}
步驟三:使用組件
這里我是在 pages/mine/mine 頁面調用 component/stepper/stepper 自定義組件
首先在mine.json中進行引用說明, 這里是設置自定義組件的標簽名和引用路徑
{
"usingComponents": {
"stepper": "../../component/stepper/stepper"
}
}
然后在mine.wxml調用組件
<!--pages/mine/mine.wxml--> <view> <!-- 調用stepper組件 --> <stepper/> </view>
步驟四:效果圖

