封装个微信小程序日期时间组件
时间: 2023-03-05 18:36:19 浏览: 94
好的,以下是一个简单的微信小程序日期时间组件的封装示例,它包括日期选择器和时间选择器:
1. 在小程序的 components 目录下创建一个名为 "datetime-picker" 的文件夹,并在该文件夹下创建一个名为 "datetime-picker.wxml" 的文件。
2. 在 datetime-picker.wxml 文件中,编写以下代码:
```html
<view class="datetime-picker">
<picker mode="date" value="{{value}}" bindchange="bindDateChange">
<view class="picker">
{{year}}年{{month}}月{{day}}日
</view>
</picker>
<picker mode="time" value="{{value}}" bindchange="bindTimeChange">
<view class="picker">
{{hour}}时{{minute}}分
</view>
</picker>
</view>
```
3. 在 datetime-picker.wxml 文件同级目录下创建一个名为 "datetime-picker.js" 的文件,并编写以下代码:
```javascript
Component({
/**
* 组件的属性列表
*/
properties: {
value: {
type: String,
value: ''
}
},
/**
* 组件的初始数据
*/
data: {
year: '',
month: '',
day: '',
hour: '',
minute: '',
},
/**
* 组件的方法列表
*/
methods: {
bindDateChange: function (e) {
const value = e.detail.value;
const date = new Date(value);
const year = date.getFullYear();
const month = date.getMonth() + 1;
const day = date.getDate();
this.setData({
year,
month,
day
})
this.triggerEvent('change', {
value: this.data.year + '-' + this.data.month + '-' + this.data.day + ' ' + this.data.hour + ':' + this.data.minute
});
},
bindTimeChange: function (e) {
const value = e.detail.value;
const date = new Date(value);
const hour = date.getHours();
const minute = date.getMinutes();
this.setData({
hour,
minute
})
this.triggerEvent('change', {
value: this.data.year + '-' + this.data.month + '-' + this.data.day + ' ' + this.data.hour + ':' + this.data.minute
});
},
},
ready: function () {
const value = this.properties.value;
if (value) {
const date = new Date(value);
const year = date.getFullYear();
const month = date.getMonth() + 1;
const day = date.getDate();
const hour = date.getHours();
const minute = date.getMinutes();
this.setData({
year,
month,
day,
hour,
minute
})
} else {
const now = new Date();
const year = now.getFullYear();
const month = now.getMonth() + 1;
const day = now.getDate();
const hour = now.getHours();
const minute = now.getMinutes();
this.setData({
year,
month,
day,
hour,
minute
})
}
}
})
```
4. 在 datetime-picker 文件夹下创建一个名为 "datetime-picker.wxss" 的文件,并编写以下代码:
```css
.datetime-picker {
display: flex;
justify-content: space-between;
align-items: center;
}
.picker {
height: 100%;
display: flex;
justify-content: