Vue implementa el tiempo/cuenta regresiva del juego

Requisitos: Obtener la hora de inicio y finalización del juego. (¡¡La carrera está contando!!)

(1) Si no es la hora de inicio del juego, se mostrará 00:00:00.

(2) Si es la hora de inicio pero no la hora de finalización, mostrará cuánto tiempo ha pasado desde la hora de inicio.

(3) Si se supera la hora de finalización, se mostrará el tiempo total, que es la hora de finalización del juego menos la hora de inicio.

     isBeforeStart: el juego aún no ha comenzado isOver el juego ha terminado

        <p>比赛用时</p>
        <p class="match-time" v-if="isBeforeStart">00:00:00</p>
        <p class="match-time" v-else-if="isOver">{
   
   { formatTime(totalTime) }}</p>
        <p class="match-time" v-else>{
   
   { formatTime(useTime) }}</p>

definido en los datos

data(){
  return{
    startTime: '2023-04-13 20:33:22',//比赛开始时间
    endTime: '2023-04-14 21:33:22',//比赛结束时间
    useTime: '', // 倒计时
    timerMatch: null //计时器
  }
},
mounted(){
  this.getTime()
},
beforeDestroy () {
  this.timerMatch = null  //销毁计时器,避免内存泄露
},
computed: {  //计算属性
  isBeforeStart () {
    return new Date() < this.startTime
  },
  isOver () {
    return new Date() > this.endTime
  },
  totalTime () {
    return Math.floor((new Date(this.endTime) - new Date(this.startTime)) / 1000)
  }
},
methods:{
  getTime(){ 
   //......一般是接口返回比赛时间,自己的逻辑自行修改......
    this.startTime = new Date(this.startTime)
    this.endTime = new Date(this.endTime)
    this.useTime = Math.floor((new Date() - this.startTime) / 1000)
    this.timerMatch = setInterval(() => {
      this.useTime = Math.floor((new Date() - this.startTime) / 1000)
         if (new Date() >= this.endTime) {
           clearInterval(this.timerMatch)
          }
      }, 1000)
  }
}

Cuenta regresiva del juego: si el requisito es una cuenta regresiva del juego, se puede calcular cambiando startTime a endTime de acuerdo con la lógica correspondiente.

Supongo que te gusta

Origin blog.csdn.net/enhenglhm/article/details/130316906
Recomendado
Clasificación