需求:是点击确定才变更时间
element的组件是change就会改变双向绑定的值,
看到源码有handleClose方法,于是尝试在handleClose方法动收件,并且套了一层,封装这个DateTimePicker组件,
缺点:
点击确定后,派发给父组件的值,在提交前需要处理转化一下格式,但是好歹算是实现了
父组件:
<picker
:disabled="false"
v-model="timer"
format="yyyy.MM.dd HH:mm"
value-format="yyyy.MM.dd HH:mm"
type="datetime"
placeholder="选择日期时间"
default-time="12:00:00"
>
</picker>
...
components: {
'picker': import 'xxx/picker.vue',
},
data(){
return{
timer:""
}
},
子组件:
<template>
<el-date-picker
ref="datePicker"
v-bind="$attrs"
v-model="pValue"
@change="handleChange"></el-date-picker>
</template>
<script>
module.exports = {
name: "picker",
data() {
return {
pValue: "",
clickOutsideFlag: false,
childHandleClose: null
};
},
props: {
value: {
type: [Date, String, Array],
required: true
}
},
created() {
//不用moment的话自己处理一下时间格式
const timer = moment(this.value, "YYYYMMDDHHmmss").format(`YYYY.MM.DD HH:mm`);
this.$emit('input', timer);
},
mounted() {
this.childHandleClose = this.$refs.datePicker.handleClose;
this.$refs.datePicker.handleClose = this.handleClose;
},
watch: {
value(val) {
if (val === null || val === undefined) {
this.pValue = "";
} else {
this.pValue = val;
}
this.updateInput();
},
},
methods: {
handleChange() {
if (!this.clickOutsideFlag) {
this.updateInput();
this.$emit("change", this.pValue);
} else {
this.clickOutsideFlag = false;
this.pValue = this.value;
}
},
handleClose() {
if (this.$refs.datePicker.pickerVisible) {
this.clickOutsideFlag = true;
this.childHandleClose();
}
},
updateInput() {
this.$emit('input', this.pValue);
this.$refs.datePicker.$refs.reference.$refs.input.value = this.value;
}
}
};
</script>