商品列表和商品詳情常常用到數量的加減,比如這個樣子:
傳入一個最大值和最小值,在這個範圍可以自由加減,
上代碼:wxml:
<view class="count_box">
<view class="count_group">
<view class="count_btn" data-tar="minus" bind:tap="tapBtn">
<image src="/assets/imgs/icon/icon-minus.png" hidden="{{count<=min}}"></image>
<image src="/assets/imgs/icon/icon-minus-disabled.png" hidden="{{count>min}}"></image>
</view>
<view class="count_input">
<input value="{{count}}" bind:blur="blurHandle" bindinput="inputHandle"></input>
</view>
<view class="count_btn" data-tar="plus" bind:tap="tapBtn">
<image src="/assets/imgs/icon/icon-plus.png" hidden="{{count>=max}}"></image>
<image src="/assets/imgs/icon/icon-plus-disabled.png" hidden="{{count<max}}"></image>
</view>
</view>
<view wx:if='{{errorMsg}}' class="errorMsg">{{errorMsg}}</view>
</view>
.count_box {
width: 230rpx;
.count_group {
display: flex;
justify-content: space-between;
align-items: center;
padding: 0 20rpx;
height: 70rpx;
border: 2rpx solid #ccc;
border-radius: 4rpx;
.count_btn {
width: 42rpx;
height: 42rpx;
padding: 7rpx;
}
.count_input{
width: 80rpx;
input{
text-align: center;
font-size: 36rpx;
}
}
}
.errorMsg {
margin-top: 4rpx;
font-size: 26rpx;
color: #ff6600;
text-align: right;
}
}
js:(重點)Component({
properties: {
code:{
type:String,
value:null
},
max: {//傳如的最大值
type: Number,
value: 5
},
min: {
type: Number,
value: 0
},
count: {
type: Number,
value: 1
},
errorMsg: {
type:String,
value: ''
}
},
data: {},
methods: {
/*邏輯事件*/
setNewCount:function(count){
let _count=this.data.count;
if(count!=_count){
let _data={};
_data.count=count;
if(this.data.code)_data.code=this.data.code;
this.triggerEvent('callChangeCount', _data);
this.setData({ count:count });
}
},
/*頁面交互*/
tapBtn: function(evt) {
const _tar=evt.currentTarget.dataset.tar;
const _max=this.data.max;
const _min=this.data.min;
let _count=this.data.count;
if(_tar=='plus'){
if(_count<_max){
_count++;
}
}else{
if(_count>_min){
_count--;
}
};
this.setNewCount(_count);
},
blurHandle: function(evt){
let _value=evt.detail.value;
const _max=this.data.max;
const _min=this.data.min;
let _count=_value;
if(_count>_max)_count=_max;
if(_count<_min)_count=_min;
this.setNewCount(_count);
},
inputHandle:function(evt){
let _value=evt.detail.value;
this.setData({ count:_value });
}
}
})
json:
{
"component": true,
"usingComponents": {}
}
說明:組件中的json文件代碼基本每次都保持不變,都是固定格式
js文件中通過頁面分別傳入最大值最小值,裏面的加號減號兩種不同狀態分別是用了不同的圖標來表示,因爲使用+、-號和icon圖標顯示的效果並不好。
最近寫的組件代碼的頁面引入我就不寫了,又不會的想提問的評論區提問,看到我會說的