123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163 |
- <template>
- <view class="u-count-down">
- <slot>
- <text class="u-count-down__text">{{ formattedTime }}</text>
- </slot>
- </view>
- </template>
- <script>
- import props from './props.js';
- import {
- isSameSecond,
- parseFormat,
- parseTimeData
- } from './utils';
-
- export default {
- name: 'u-count-down',
- mixins: [uni.$u.mpMixin, uni.$u.mixin, props],
- data() {
- return {
- timer: null,
-
- timeData: parseTimeData(0),
-
- formattedTime: '0',
-
- runing: false,
- endTime: 0,
- remainTime: 0,
- }
- },
- watch: {
- time(n) {
- this.reset()
- }
- },
- 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.millisecond) {
- 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()
- }
- }, 50)
- },
-
- 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('finish')
- }
- },
-
- reset() {
- this.pause()
- this.remainTime = this.time
- 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()
- }
- }
- </script>
- <style
- lang="scss"
- scoped
- >
- @import "../../libs/css/components.scss";
- $u-count-down-text-color:$u-content-color !default;
- $u-count-down-text-font-size:15px !default;
- $u-count-down-text-line-height:22px !default;
- .u-count-down {
- &__text {
- color: $u-count-down-text-color;
- font-size: $u-count-down-text-font-size;
- line-height: $u-count-down-text-line-height;
- }
- }
- </style>
|