bootstrap中比较用的日期选择器插件是bootstrap-datetimepicker,默认样式如下:
下面先给出在页面中实际使用的例子:
<div id="app">
<div class="form-group col-xs-4">
<label class="control-label col-xs-3">startTime:</label>
<div class="col-xs-9">
<input id="startTime" class="form-control" autocomplete="off"
v-model="startTime"/>
</div>
</div>
</div>
<script>
new Vue({
el: '#app',
data () {
return {
startTime: '',
endTime: ''
}
},
mounted: function() {
this.dateInit()
},
methods: {
dateInit: function() {
now = new Date()
now.setMinutes(now.getMinutes() - 1)
startDate = new Date()
startDate.setDate(startDate.getDate() - 89)
$('#startTime').datetimepicker({
startDate: startDate,
endDate: new Date(),
todayBtn: 1,
autoclose: 1,
todayHighlight: 1,
startView: 'month',
forceParse: 0,
minView: "day",
format: 'yyyy/mm/dd hh'
})
$('#startTime').datetimepicker('setDate', now)
this.startTime = $('#startTime').val()
$('#startTime').datetimepicker()
.on('hide', (ev) => {
this.startTime = $('#startTime').val()
})
},
}
})
</script>
分析其中一些需要注意的地方:
1. datetimepicker初始化的时机,
建议在mounted阶段进行初始化,vue.js在mounted阶段html已经创建完毕,这是才可以正常使用jquery进行初始化。
2. 可选范围
默认没有限制可选范围,通过初始化是指定startDate 和endDate限制范围。在范围内的时间点都可以选择,其余的不能选择。
3. 默认值
默认值设置有两种方式,上面的例子中使用setDate事件设置默认值,还有一种通过初始字段initialDate:new Date()设置默认值(个人测试时无效)。注意当默认值在可选范围之外时无效,无法赋值,以上例子中为默认值偏移一分钟。
4. vue双向绑定
需要通过datetimepicker的时间进行回调,例如在设置默认只是需要为vue中的字段赋值,另外在hide事件中为vue中的字段进行赋值。