Vue 可以将页面上频繁使用的时间范围选择器,写成组件,便于前端开发
组件js文件 datepick.js
Vue.component('select-range-datetime', {
props:{
start_date: {
type: String,
default: '',
},
end_date: {
type: String,
default: '',
},
index: {
type: Number,
require: true,
}
},
mounted(){
this.dateRange = [this.start_date, this.end_date];
},
data: function () {
return {
dateRange: [],
pickerOptions: {
shortcuts: [{
text: '最近一周',
onClick(picker) {
const end = new Date();
const start = new Date();
start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
picker.$emit('pick', [start, end]);
}
}, {
text: '最近一个月',
onClick(picker) {
const end = new Date();
const start = new Date();
start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
picker.$emit('pick', [start, end]);
}
}, {
text: '最近三个月',
onClick(picker) {
const end = new Date();
const start = new Date();
start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
picker.$emit('pick', [start, end]);
}
}]
}
}
},
methods: {
setDate: function(e) {
var val = {};
val.datetime = e;
val.index = this.index;
console.log(val);
this.$emit('datetimeselected', val);
}
},
template: `
<div>
<el-date-picker
v-model="dateRange"
type="datetimerange"
align="right"
unlink-panels
range-separator="至"
start-placeholder="开始时间"
end-placeholder="结束时间"
:picker-options="pickerOptions"
value-format="yyyy-MM-dd HH:mm:ss"
:default-time="['08:00:00', '12:00:00']"
@change="setDate">
</el-date-picker>
</div>
`,
});
注意:template 中的html部分,一定要有个总的元素包在最外层,不可以有并列元素
页面使用时就比较简单了
<script src="datepicker.js"></script>
<div id="app">
<select-range-datetime start_date="2010-10-09 07:00:00" end_date="2020-07-09 12:00:00" @datetimeselected="handleTime"></select-range-datetime>
</div>
<script>
var app = new Vue({
el: '#app',
data: {
},
methods:{
handleTime: function(e){
console.log(e);
if (e) {
var start_time = e[0];//选择后返回的开始时间
var end_time = e[1];//选择后返回的结束时间
} else {
var start_time = '';
var end_time = '';
}
}
}
</script>
一个页面,可以多次使用,不用在页面上写太多的变量与js,很方便