1,注册DataTimePicker组件
import { DatetimePicker } from 'vant'
Vue.use(DatetimePicker)
2,在UserEdit.vue页面使用, 定义相关变量
<!-- 修改时间 -->
<van-popup v-model="isShowBirth" position="bottom" style="height: 50%" round>
<!-- 日期选择控件 -->
<van-datetime-picker
v-model="currentDate"
type="date"
title="选择出生日期"
:min-date="minDate"
:max-date="maxDate"
:show-toolbar="true"
/>
</van-popup>
<script>
export default {
data () {
return {
// ...
isShowBirth: false, // 显示时间选择器
minDate: new Date(1900, 0, 1), // 最小的可选的日期
maxDate: new Date(), // 最大的可选日期
currentDate: new Date() // 当前日期
}
},
}
</script>
3,点击单元格, 弹出时间选择组件
<van-cell title="生日" is-link :value="profile.birthday" @click="isShowBirth = true"/>
4,绑定事件, 实现功能
<!-- 修改时间 -->
<van-popup
v-model="isShowBirth"
position="bottom"
style="height: 50%"
round>
<!-- 日期选择控件 -->
<van-datetime-picker
v-model="currentDate"
type="date"
title="选择出生日期"
:min-date="minDate"
:max-date="maxDate"
:show-toolbar="true"
@cancel="isShowBirth = false"
@confirm="confirmFn"/>
</van-popup>
<script>
import moment from 'moment'
export default {
methods: {
// 弹出时间选择框
showBirthFn () {
this.isShowBirth = true
this.currentDate = new Date(this.profile.birthday) // 设置data组件默认显示时间
},
// 时间选择
async confirmFn () {
// console.log(this.currentDate instanceof Date)
// this.currentDate里值是日期对象
// 但是后台要"年-月-日"格式字符串参数值
console.log(this.currentDate)
const dateStr = moment(this.currentDate).format('YYYY-MM-DD')
await updateProfileAPI({
birthday: dateStr
})
// 前端页面同步
this.profile.birthday = dateStr
// 时间选择器关闭
this.isShowBirth = false
}
}
}
</script>