需求:在微信小程序上,点击时间按钮,从底部弹起时间选择器,在一进入页面的时候,显示当前年月日,当使用选择器切换时间的时候,所选日期要同步到选择器上,并且结束时间不能大于当前年月日,最后当每次重新选择时间时,拿到当前选择时间,去请求接口。
<view class="selectTime">
<picker mode="date" fields="month" :start="startDate" :end="endDate" @change="bindDateChange">
<view class="timeShow" v-cloak>{{date}}月</view>
</picker>
</view>
注意:mode为选择器的类型,共五种:普通选择器,多列选择器,时间选择器,日期选择器,省市区选择器,默认是普通选择器
mode="date"为时间选择器
fields为选择器的格式,分别为:year,month,day,fields="month"表示选择器只显示年月,fields="year"表示选择器只显示年,以此类推
start为定义的开始范围,end为定义结束的范围
export default {
data() {
const currentDate = this.getDate({
format: true
})
return {
date: currentDate
}
}
computed: {
// 定义开始的时间
startDate() {
return this.getDate('start')
},
// 定义结束的时间
endDate() {
return this.getDate('end')
}
}
}
- 第三步:当一进入页面,就获取当前时间,并把时间显示在选择器
methods: {
// 获取当前时间
getDate(type) {
this.year = new Date().getFullYear()
this.month = new Date().getMonth() + 1
this.day = new Date().getDate()
if (type === 'start') {
this.year = this.year - 60
} else if (type === 'end') {
this.year = this.year
}
this.month = this.month > 9 ? this.month : '0' + this.month
this.day = this.day > 9 ? this.day : '0' + this.day
// 核心:该结果将会直接显示在时间选择器上
return `${this.year}-${this.month}-${this.day}`
}
}
}
- 第四步:当选择时间时,将所选时间显示在时间选择器上
methods: {
bindDateChange(params) {
// date的时间就会直接显示在组件上
this.date = params.detail.value
},
}
methods: {
bindDateChange(params) {
this.date = params.detail.value
// 将2019-01-08截取成2019 01
this.year = parseInt(params.detail.value.substring(0,4))
this.months = parseInt(params.detail.value.substring(5))
this.month = this.months > 9 ? this.months : "0" + this.months
this.getTotal()
},
getTotal() {
this.$api.post('', {
year: this.year,
month: this.month
}).then((res) => {
},
}