倒計時組件
倒計時組件
<template> <div class="container"> <!-- 一個元素顯示倒計時 --> <div v-show="isEndStatus" v-if="!manyElement" :style="{ color }">{{ countDownItem }}</div> <!-- 多元素倒計時 --> <div v-show="isEndStatus" :style="{ color }" v-else> <slot name="customMany" :slot-scope="splitElement"> <span v-for="(item, index) in splitElement" :key="index"> {{ index !== splitElement.length - 1 ? item + separator : item }} </span> </slot> </div> </div> </template>
<script> export default { name: 'count-down', props: { // 結束的時間毫秒數 actEndTime: { type: Number, default: Date.now() + 10000 }, // 顯示倒計時格式 countDownList: { type: String, default: 'dd-hh-mm-xx' }, // 字體顏色 color: { type: String, default: '#000000' }, // 分隔符 separator: { type: String, default: '' }, // 是否開啟多元素顯示效果 manyElement: { type: Boolean, default: false } }, data () { return { countDownItem: '', newTime: null, // 倒計時是否執行完畢 isEndStatus: true } }, computed: { // 多元素顯示處理 splitElement () { if (this.manyElement) { return this.countDownItem.split(this.separator || ' ') } return this.countDownItem.split(this.separator) } }, methods: { timeFormat (param) { return param < 10 ? '0' + param : param }, countDown () { const interval = setInterval(() => { const newTime = new Date().getTime() const endTime = new Date(this.actEndTime + 2000).getTime() let obj = null if (endTime - newTime > 0) { const time = (endTime - newTime) / 1000 const day = parseInt(time / (60 * 60 * 24)) const hou = parseInt((time % (60 * 60 * 24)) / 3600) const min = parseInt(((time % (60 * 60 * 24)) % 3600) / 60) const sec = parseInt(((time % (60 * 60 * 24)) % 3600) % 60) obj = { dd: this.timeFormat(day), hh: this.timeFormat(hou), mm: this.timeFormat(min), xx: this.timeFormat(sec) } if (this.newTime) { this.$emit('start-click', this.newTime) } } else { // 倒計時結束 obj = { dd: '00', hh: '00', mm: '00', xx: '00' } this.isEndStatus = false clearInterval(interval) this.$emit('end-click', this.countDownItem) } const timeList = this.countDownList.split('-') const dateList = ['日', '時', '分', '秒'] this.newTime = '' // 循環判斷如果用戶傳過來的日期,包含對象中的屬性,那麼就使用該屬性的值 Object.keys(obj).forEach((key, index) => { if (timeList.includes(key)) { // 如果是最後一組,就不加分隔符 const separLen = index !== dateList.length - 1 ? this.separator : '' // 判斷數據佔位元素問題 if (this.manyElement) { this.newTime += obj[key] += dateList[index] + ' ' + separLen } else { this.newTime += obj[key] += dateList[index] += separLen } } }) this.countDownItem = this.newTime }, 1000) } }, mounted () { this.countDown() } } </script>
// 參數詳解 /* 1.actEndTime(Number):倒計時結束的時間,毫秒數 2.countDownList(String):倒計時顯示的時間要求(dd(日)-hh(時)-mm(分)-xx(秒)) 3.color(String):字體顏色 4.separator(String):分隔符 5.manyElement(Boolean):是否開啟多元素顯示效果 */