使用 Element+vue实现开始时间结束时间限制
html部分:
1 <div> 2 <div style=" width: 220px; margin: 20px auto 0;"> 3 <el-date-picker 4 v-model="startDate" 5 type="date" 6 placeholder="选择开始日期" 7 format="yyyy/MM/dd " 8 value-format="timestamp" 9 :picker-options="pickerOptionsStart" 10 @change="changeStart"> 11 </el-date-picker> 12 </div> 13 <div style=" width: 220px; margin: 20px auto 0;"> 14 <el-date-picker 15 v-model="endDate" 16 type="date" 17 placeholder="选择结束日期" 18 format="yyyy/MM/dd " 19 value-format="timestamp" 20 :picker-options="pickerOptionsEnd" 21 @change="changeEnd"> 22 </el-date-picker> 23 </div> 24 </div>
js部分:
1 data() { 2 return { 3 pickerOptionsStart: {}, 4 pickerOptionsEnd: {}, 5 startDate: '', // 开始日期 6 endDate: '', // 结束日期 7 } 8 } 9 10 11 12 methods: { 13 14 changeStart() { // 限制开始时间 15 this.pickerOptionsEnd = Object.assign({}, this.pickerOptionsEnd, { 16 disabledDate: (time) => { 17 if (this.startDate) { 18 return time.getTime() < this.startDate 19 } 20 } 21 }) 22 }, 23 24 changeEnd() { // 限制结束时间 25 console.log(this.endDate); 26 this.pickerOptionsStart = Object.assign({}, this.pickerOptionsStart, { 27 disabledDate: (time) => { 28 if (this.endDate) { 29 return time.getTime() > this.endDate 30 } 31 } 32 }) 33 }, 34 35 beautifyTimeFormat(value) { // 时间戳转换时间格式 36 if (value == null) { 37 return ''; 38 } else { 39 let date = new Date(value); 40 let y = date.getFullYear();// 年 41 let MM = date.getMonth() + 1;// 月 42 MM = MM < 10 ? ('0' + MM) : MM; 43 let d = date.getDate();// 日 44 d = d < 10 ? ('0' + d) : d; 45 return y + '-' + MM + '-' + d; 46 } 47 } 48 }
html写法2
1 <script src="//unpkg.com/vue/dist/vue.js"></script> 2 <script src="//unpkg.com/element-ui@2.3.8/lib/index.js"></script> 3 <div id="app"> 4 <template> 5 <div class="block"> 6 <span class="demonstration">起始日期</span> 7 <el-date-picker v-model="startDate" type="date" placeholder="选择日期" :picker-options="pickerOptionsStart" @change="changeEnd"> 8 </el-date-picker> 9 </div> 10 11 <div class="block"> 12 <span class="demonstration">截止日期</span> 13 <el-date-picker v-model="endDate" type="date" placeholder="选择日期" :picker-options="pickerOptionsEnd" @change="changeStart"> 14 </el-date-picker> 15 </div> 16 </template> 17 </div>
js部分:
1 var Main = { 2 data() { 3 return { 4 pickerOptionsStart: {}, 5 pickerOptionsEnd:{}, 6 startDate: '', 7 endDate: '', 8 }; 9 }, 10 methods:{ 11 changeStart (){ 12 this.pickerOptionsStart = Object.assign({},this.pickerOptionsStart,{ 13 disabledDate: (time) => { 14 return time.getTime() > this.endDate 15 } 16 }) 17 }, 18 changeEnd (){ 19 this.pickerOptionsEnd = Object.assign({},this.pickerOptionsEnd,{ 20 disabledDate: (time) => { 21 return time.getTime() < this.startDate 22 } 23 }) 24 } 25 } 26 }; 27 var Ctor = Vue.extend(Main) 28 new Ctor().$mount('#app')
css部分:
1 @import url("//unpkg.com/element-ui@2.3.8/lib/theme-chalk/index.css"); 2 3 .block{ 4 margin-top:10px; 5 }