小程序自定义picker实现年月日时分和年月日时分秒时间选择器
最近在做公司的一个小程序项目中需要用到选择年月日时分秒的地方,然后我去小程序开发文档上看了看好像没有直接可以选择年月日时分秒的选择器组件,所以周末我就花了些时间封装了一个可以选择年月日时分秒和年月日时分的时间选择器组件。希望能够帮助到有需要的人!
代码我已经提交到码云上面了,可以通过这个链接下载我的代码:
https://gitee.com/yuanyifei666/wxDateTimePicker.git
下载后在components目录下的date-time-picker就是我封装的时间选择器组件了
直接把我的这date-time-picker目录复制到你的项目里,然后在要使用到该组件的页面的json文件中引入该组件,注意路径要正确!(我这里以index页面为例子)
{
"usingComponents": {
"date-time-picker": "/components/date-time-picker/index"
},
"navigationBarTitleText": "封装时间选择器组件"
}
然后在index.wxml文件中使用该组件
<!--pages/index/index.wxml-->
<date-time-picker
mode="dateminute"
value="{
{dateMinute}}"
bindchange="selectDateMinuteChange">
<view class="show-date-time-box">年月日时分: {
{
dateMinute}}</view>
</date-time-picker>
<date-time-picker
mode="datetime"
value="{
{dateSecond}}"
bindchange="selectDateSecondChange">
<view class="show-date-time-box">年月日时分秒: {
{
dateSecond}}</view>
</date-time-picker>
属性说明:
1、mode:选择器类型
mode 的合法值:
dateminute: 年月日时分选择器(2019-11-30 11:03)
datetime: 时间选择器(2019-11-30 11:03:17)
2、value:选择器的值
3、bindchange:value 改变时触发 change 事件,可以获得选择的值
index.js文件里的代码如下:
//index.js
//获取应用实例
const app = getApp()
Page({
data: {
dateMinute: '',
dateSecond: ''
},
/**
* 年月日时分选择类型的回调函数,可以在该函数得到选择的时间
*/
selectDateMinuteChange(ev) {
this.setData({
dateMinute: ev.detail.value
})
},
/**
* 年月日时分秒选择类型的回调函数,可以在该函数得到选择的时间
*/
selectDateSecondChange(ev) {
this.setData({
dateSecond: ev.detail.value
})
}
})
以上就是组件简单的使用,下面就是该组件具体的实现代码了
js代码:
// components/date-time-picker/index.js
Component({
/**
* 定义组件生命周期函数
*/
lifetimes: {
attached() {
// =====初始化时间选择器====
this._initDateTimePickerFn()
},
detached() {
}
},
/**
* 对 <2.2.3 版本基础库的兼容
*/
attached() {
// =====初始化时间选择器====
this._initDateTimePickerFn()
},
detached() {
},
/**
* 组件相关配置项
*/
options: {
multipleSlots: true // 开启使用多个插槽
},
/**
* 组件的属性列表
*/
properties: {
mode: {
// 选择器类型
type: String,
require: true
},
value: