<template> <date-picker :class="['app-date-range', 'app-date-range--' + type]" :type="rangeType" :value="realVal" :placeholder="placeholder" :disabled="disabled" transfer @on-change="onChange" @on-open-change="onOpenChange" ></date-picker> </template> <script lang="ts"> import { Vue, Component, Prop, Watch } from "vue-property-decorator"; @Component({}) export default class AppDateRange extends Vue { /** * 是否禁用 * * @type {string} * @memberof AppDateRange */ @Prop({ default: false }) public disabled?: boolean; /** * placeholder * * @type {string} * @memberof AppDateRange */ @Prop({ default: "请选择时间" }) public placeholder?: string; /** * 日期值格式化 * * @type {string} * @memberof AppDateRange */ @Prop() public valueFormat?: string; /** * 数据类型 * * @type {string} * @memberof AppDateRange */ @Prop({ default: "datetime" }) public type?: "datetime" | "date"; /** * 开始属性名称 * * @type {string} * @memberof AppDateRange */ @Prop() public startField?: string; /** * 结束属性名称 * * @type {string} * @memberof AppDateRange */ @Prop() public endField?: string; /** * 传入表单数据 * * @type {*} * @memberof AppDateRange */ @Prop() public data?: any; /** * 实际组件维护的值 * * @type {*} * @memberof AppDateRange */ public realVal: any[] = []; /** * 是否修改过数据 * @type {boolean} * @memberof AppDateRange */ public modified: boolean = false; /** * iview组件类型` * * @type {string} * @memberof AppDateRange */ get rangeType() { switch (this.type) { case "date": return "daterange"; default: return "datetimerange"; } } /** * 生命周期 * * @type {string} * @memberof AppDateRange */ created() { if (!this.startField) { this.$Notice.error({ title: this.$t("app.commonWords.wrong") as string, desc: "没有配置开始属性", }); } if (!this.endField) { this.$Notice.error({ title: this.$t("app.commonWords.wrong") as string, desc: "没有配置结束属性", }); } } /** * 监控表单属性 data 值 * * @memberof AppDateRange */ @Watch("data", { deep: true, immediate: true }) onDataChange(newVal: any, oldVal: any) { if (newVal && this.startField && this.endField) { this.realVal = [newVal[this.startField], newVal[this.endField]]; this.modified = false; console.log(this.realVal); } } /** * iview组件值变更事件(只更新realVal,不抛出) * * @memberof AppDateRange */ onChange(values: any[]) { this.realVal = values; this.modified = true; if(values[0]==='' && values[1] === ''){ //清空的情况,直接抛值,openChange会先触发,或不触发。 this.$emit("change", this.startField!, null); this.$emit("change", this.endField!, null); } } /** * iview组件值关闭事件(如果数据有变更,则抛出change事件) * * @memberof AppDateRange */ onOpenChange(isOpen: boolean) { if (!isOpen && this.modified) { const [start, end] = this.realVal; this.$emit("change", this.startField!, start); this.$emit("change", this.endField!, end); } } } </script> <style lang="scss"> @import "./app-date-range.scss"; </style>