123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175 |
- <template>
- <view class="u-count-down">
- <slot>
- <text class="u-count-down__text" :style="customStyle">{{ formattedTime }}</text>
- </slot>
- </view>
- </template>
- <script>
- import { isSameSecond, parseFormat, parseTimeData } from "./utils";
- export default {
- name: "u-count-down",
- emits: ["change", "end", "finish"],
- props: {
-
- timestamp: {
- type: [String, Number],
- default: 0
- },
-
- format: {
- type: String,
- default: "DD:HH:mm:ss"
- },
-
- autoStart: {
- type: Boolean,
- default: true
- },
- customStyle: {
- type: [String, Object],
- default: ""
- }
- },
- data() {
- return {
- timer: null,
-
- timeData: parseTimeData(0),
-
- formattedTime: "0",
-
- runing: false,
- endTime: 0,
- remainTime: 0
- };
- },
- watch: {
- timestamp(n) {
- this.reset();
- },
- format(newVal, oldVal) {
- this.pause();
- this.start();
- }
- },
- mounted() {
- this.init();
- },
- methods: {
- init() {
- this.reset();
- },
-
- start() {
- if (this.runing) return;
-
- this.runing = true;
-
- this.endTime = Date.now() + this.remainTime;
- this.toTick();
- },
-
- toTick() {
- if (this.format.indexOf("SSS") > -1) {
- this.microTick();
- } else {
- this.macroTick();
- }
- },
- macroTick() {
- this.clearTimeout();
-
-
- this.timer = setTimeout(() => {
-
- const remain = this.getRemainTime();
-
- if (!isSameSecond(remain, this.remainTime) || remain === 0) {
- this.setRemainTime(remain);
- }
-
- if (this.remainTime !== 0) {
- this.macroTick();
- }
- }, 30);
- },
- microTick() {
- this.clearTimeout();
- this.timer = setTimeout(() => {
- this.setRemainTime(this.getRemainTime());
- if (this.remainTime !== 0) {
- this.microTick();
- }
- }, 30);
- },
-
- getRemainTime() {
-
- return Math.max(this.endTime - Date.now(), 0);
- },
-
- setRemainTime(remain) {
- this.remainTime = remain;
-
- const timeData = parseTimeData(remain);
- this.$emit("change", timeData);
-
- this.formattedTime = parseFormat(this.format, timeData);
-
- if (remain <= 0) {
- this.pause();
- this.$emit("end");
- this.$emit("finish");
- }
- },
-
- reset() {
- this.pause();
- this.remainTime = this.timestamp;
- this.setRemainTime(this.remainTime);
- if (this.autoStart) {
- this.start();
- }
- },
-
- pause() {
- this.runing = false;
- this.clearTimeout();
- },
-
- clearTimeout() {
- clearTimeout(this.timer);
- this.timer = null;
- }
- },
-
- beforeDestroy() {
- this.clearTimeout();
- },
-
-
-
- beforeUnmount() {
- this.clearTimeout();
- },
-
- };
- </script>
- <style lang="scss"></style>
|