组件使用了vant-weapp UI组件库,结合van-popup,van-datetimepicker封装。
组件页面如下:
<view class="ui-datetime-picker">
<view class="model-wrapper">
<van-cell custom-class="global-cell" title-class="{{ !myValue ? 'cell-title-placeholder' : '' }}"
title="{{ myValue || placeholder }}" is-link="{{ !readonly }}" border="{{ false }}" bind:click="showPicker">
</van-cell>
<view class="icon-close" wx:if="{{ clearable && myValue }}">
<van-icon name="close" catchtap="handleClear"></van-icon>
</view>
</view>
<van-popup show="{{ popShow }}" custom-style="padding-bottom: 40rpx" position="bottom"
bind:click-overlay="closePopup">
<view class="picker-title" catchtap="closePopup">
<view class="arrow-down">
<iconfont class="arrow-down-icon" name="i_arrow" size="72"></iconfont>
</view>
<view>{{title}}</view>
</view>
<van-datetime-picker column-class="ui-datetime-column" value="{{ currentDate }}" type="datetime" min-date="{{ minDate }}" max-date="{{ maxDate }}"
show-toolbar="{{ false }}" visible-item-count="5" bind:change="onChange" />
<van-button data-datestr="{{ currentDate }}" class="picker-btn" type="info" block bind:click="handleOK">确定</van-button>
</van-popup>
</view>
组件js如下:
// Components/PopDateTimePicker/index.js
import { eptimes } from '../../utils/eptimes';
Component({
/**
* 组件的属性列表
*/
properties: {
title: {
type: String,
value: ''
},
readonly: {
type: Boolean,
value: false
},
initData: {
type: String,
value: '',
observer: function(newVal) {
if (newVal) {
this.setData({
myValue: eptimes.outTime(new Date(newVal), 'yyyy/MM/dd HH:mm:ss')
})
} else {
this.setData({
myValue: ''
})
}
}
},
placeholder: {
type: String,
value: ''
},
minDate: {
type: null,
value: new Date(1990, 1, 1).getTime()
},
maxDate: {
type: null,
value: new Date(2099, 12, 31).getTime()
},
clearable: {
type: Boolean,
value: false
}
},
options: {
styleIsolation: 'shared'
},
/**
* 组件的初始数据
*/
data: {
myValue: '',
popShow: false,
currentDate: new Date().getTime(),
},
/**
* 组件的方法列表
*/
methods: {
onChange(event) {
let dateArr = event.detail.getValues();
let dateStr = new Date(`${dateArr.slice(0,3).join('/')} ${dateArr.slice(3).join(':')}:00`).getTime();
this.setData({
currentDate: dateStr,
});
},
showPicker: function() {
this.setData({
popShow: true
});
},
closePopup: function() {
this.setData({
popShow: false
});
},
handleClear() {
this.setData({
myValue: ''
});
this.triggerEvent('setValue', '');
},
handleOK(e) {
const { datestr } = e.currentTarget.dataset;
console.log("aaaaaaaa:", eptimes.outTime(new Date(datestr), 'yyyy/MM/dd HH:mm:ss'));
const { currentDate } = this.data;
let timeStr = eptimes.outTime(new Date(currentDate), 'yyyy/MM/dd HH:mm:ss');
this.setData({
myValue: timeStr,
popShow: false
})
this.triggerEvent('setValue', this.data.myValue);
}
}
})
其中,onChang函数里面setData后获取到的currentData属性值是最新的,但是页面里面data-datestr属性currentDate和handleOK 里面取出的this.data.currentDate始终为上一次的结果。这个算是组件bug还是小程序数据绑定产生的bug呢?尝试了很多种情况setData与this.data数据都无法同步