123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149 |
- <template>
- <view class="tn-code-class tn-code">
-
- </view>
- </template>
- <script>
- export default {
- name: 'tn-verification-code',
- props: {
-
- seconds: {
- type: Number,
- default: 60
- },
-
- startText: {
- type: String,
- default: '获取验证码'
- },
-
- countDownText: {
- type: String,
- default: 's秒后重新获取'
- },
-
- endText: {
- type: String,
- default: '重新获取'
- },
-
- keepRunning: {
- type: Boolean,
- default: false
- },
-
- uniqueKey: {
- type: String,
- default: ''
- }
- },
- data() {
- return {
- timer: null,
- secNum: this.seconds,
-
- canGetCode: true
- }
- },
- watch: {
- seconds: {
- handler(n) {
- this.secNum = n
- },
- immediate: true
- }
- },
- mounted() {
- this.checkKeepRunning()
- },
- beforeDestroy() {
- this.setTimeToStorage()
- if (this.timer) {
- clearInterval(this.timer)
- this.timer = null
- }
- },
- methods: {
-
- checkKeepRunning() {
-
- let lastTimestamp = Number(uni.getStorageSync(this.uniqueKey + '_$tCountDownTimestamp'))
- 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 + '_$tCountDownTimestamp')
-
- 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.countDownText.replace(/s|S/, this.secNum))
- this.setTimeToStorage()
- this.timer = setInterval(() => {
- if (--this.secNum) {
- this.changeEvent(this.countDownText.replace(/s|S/, this.secNum))
- } else {
-
- this.reset()
- this.$emit('end')
- }
- }, 1000)
- },
-
- reset() {
- this.canGetCode = true
- if (this.timer) {
- clearInterval(this.timer)
- this.timer = null
- }
- 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.setStorageSync(this.uniqueKey + '_$tCountDownTimestamp', nowTimestamp + this.secNum)
- }
- }
- }
- }
- </script>
- <style lang="scss" scoped>
- .tn-code {
- width: 0;
- height: 0;
- position: fixed;
- z-index: -1;
- }
- </style>
|