ant-design-vue/components/statistic/Countdown.tsx

89 lines
2.0 KiB
TypeScript
Raw Normal View History

2020-10-17 03:51:17 +00:00
import { defineComponent } from 'vue';
import moment from 'moment';
import interopDefault from '../_util/interopDefault';
2020-10-17 03:51:17 +00:00
import initDefaultProps from '../_util/props-util/initDefaultProps';
import Statistic, { StatisticProps } from './Statistic';
2020-10-17 03:51:17 +00:00
import { formatCountdown, countdownValueType, FormatConfig } from './utils';
const REFRESH_INTERVAL = 1000 / 30;
2020-10-17 03:51:17 +00:00
function getTime(value?: countdownValueType) {
return interopDefault(moment)(value).valueOf();
}
2020-10-17 03:51:17 +00:00
export default defineComponent({
name: 'AStatisticCountdown',
2020-10-17 03:51:17 +00:00
props: initDefaultProps(StatisticProps, {
format: 'HH:mm:ss',
}),
setup() {
return {
countdownId: undefined,
} as { countdownId: number };
},
mounted() {
this.syncTimer();
},
2020-10-17 03:51:17 +00:00
updated() {
this.syncTimer();
},
beforeUnmount() {
this.stopTimer();
},
methods: {
syncTimer() {
const { value } = this.$props;
const timestamp = getTime(value);
if (timestamp >= Date.now()) {
2020-10-17 03:51:17 +00:00
this.startTimer();
} else {
2020-10-17 03:51:17 +00:00
this.stopTimer();
}
2020-10-17 03:51:17 +00:00
},
2020-10-17 03:51:17 +00:00
startTimer() {
if (this.countdownId) return;
this.countdownId = window.setInterval(() => {
(this.$refs.statistic as any).$forceUpdate();
this.syncTimer();
}, REFRESH_INTERVAL);
2020-10-17 03:51:17 +00:00
},
2020-10-17 03:51:17 +00:00
stopTimer() {
const { value } = this.$props;
if (this.countdownId) {
clearInterval(this.countdownId);
this.countdownId = undefined;
2020-10-17 03:51:17 +00:00
const timestamp = getTime(value);
if (timestamp < Date.now()) {
2020-10-17 03:51:17 +00:00
this.$emit('finish');
}
}
2020-10-17 03:51:17 +00:00
},
2020-10-17 03:51:17 +00:00
formatCountdown({ value, config }: { value: countdownValueType; config: FormatConfig }) {
const { format } = this.$props;
return formatCountdown(value, { ...config, format });
},
2020-10-17 03:51:17 +00:00
valueRenderHtml: node => node,
},
2020-10-17 03:51:17 +00:00
render() {
return (
<Statistic
ref="statistic"
{...{
2020-10-17 03:51:17 +00:00
...this.$props,
valueRender: this.valueRenderHtml,
formatter: this.formatCountdown,
}}
/>
);
},
});