123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129 |
- <template>
- <view class="u-code">
- <!-- 此组件功能由js完成,无需写html逻辑 -->
- </view>
- </template>
- <script>
- import props from './props.js';
-
- export default {
- name: "u-code",
- mixins: [uni.$u.mpMixin, uni.$u.mixin,props],
- data() {
- return {
- secNum: this.seconds,
- timer: null,
- canGetCode: true,
- }
- },
- mounted() {
- this.checkKeepRunning()
- },
- watch: {
- seconds: {
- immediate: true,
- handler(n) {
- this.secNum = n
- }
- }
- },
- methods: {
- checkKeepRunning() {
-
- let lastTimestamp = Number(uni.getStorageSync(this.uniqueKey + '_$uCountDownTimestamp'))
- if(!lastTimestamp) return this.changeEvent(this.startText)
-
- let nowTimestamp = Math.floor((+ new Date()) / 1000)
-
- if(this.keepRunning && lastTimestamp && lastTimestamp > nowTimestamp) {
-
- this.secNum = lastTimestamp - nowTimestamp
-
- uni.removeStorageSync(this.uniqueKey + '_$uCountDownTimestamp')
-
- this.start()
- } else {
-
- this.changeEvent(this.startText)
- }
- },
-
- start() {
-
- if(this.timer) {
- clearInterval(this.timer)
- this.timer = null
- }
- this.$emit('start')
- this.canGetCode = false
-
- this.changeEvent(this.changeText.replace(/x|X/, this.secNum))
- this.setTimeToStorage()
- this.timer = setInterval(() => {
- if (--this.secNum) {
-
- this.changeEvent(this.changeText.replace(/x|X/, this.secNum))
- } else {
- clearInterval(this.timer)
- this.timer = null
- this.changeEvent(this.endText)
- this.secNum = this.seconds
- this.$emit('end')
- this.canGetCode = true
- }
- }, 1000)
- },
-
- reset() {
- this.canGetCode = true
- clearInterval(this.timer)
- this.secNum = this.seconds
- this.changeEvent(this.endText)
- },
- changeEvent(text) {
- this.$emit('change', text)
- },
-
- setTimeToStorage() {
- if(!this.keepRunning || !this.timer) return
-
-
- if(this.secNum > 0 && this.secNum <= this.seconds) {
-
- let nowTimestamp = Math.floor((+ new Date()) / 1000)
-
- uni.setStorage({
- key: this.uniqueKey + '_$uCountDownTimestamp',
- data: nowTimestamp + Number(this.secNum)
- })
- }
- }
- },
-
- beforeDestroy() {
- this.setTimeToStorage()
- clearTimeout(this.timer)
- this.timer = null
- }
- }
- </script>
- <style lang="scss" scoped>
- @import "../../libs/css/components.scss";
- </style>
|