Vue implements 60-second countdown

Here I wrote a simple 60-second countdown similar to the verification code countdown.

Let me first tell you my thoughts:

  1. In the template section, include a DIV element with a class name of "send" and a click event bound to it @click="sendIng".
  2. Within the DIV element, two v-show instructions are used to control the display of child elements. When showTime is true, the "Send" text is displayed; when showTime is false, the value of the getTime attribute is displayed.
  3. In the script part, a data object is defined, which contains showTime, getTime and timer properties. The initial value of showTime is true, which is used to control the display of "send" text and countdown text. The initial value of getTime is 60, which is used for countdown display. timer is used to store a reference to the timer.
  4. In the sendIng method, after the click event is triggered, a timer setInterval will be set to reduce the getTime value every 1000 milliseconds. At the same time, the console will output the current getTime value.
  5. If getTime is less than or equal to 0, clear the timer clearInterval, set showTime to true, and reset getTime to 60.
    Finally, set showTime to false to toggle between displaying the "send" text and the countdown text.

Without further ado, here’s the code:

html part:

<template>
  <div>
    <div class="send" @click="sendIng">
      <div v-show="showTime">发送</div>
      <div v-show="!showTime">{
    
    {
    
     getTime }}</div>
    </div>
  </div>
</template>

css part:

<style lang="scss" scoped>
.send {
    
    
  width: 70px;
  height: 40px;
  margin-top: 50px;
  margin-left: 50px;
  border: 1px solid #3189ee;
  border-radius: 8px;
  color: #3189ee;
  text-align: center;
  line-height: 40px;
  cursor: pointer;
}
</style>

Js part:

<script>
export default {
    
    
  data() {
    
    
    return {
    
    
      showTime: true,
      getTime: 60,
      timer: "",
    };
  },
  methods: {
    
    
    //点击发送出现60秒倒计时
    sendIng() {
    
    
      let timer = setInterval(() => {
    
    
        this.getTime -= 1;
        console.log(this.getTime);
        if (this.getTime <= 0) {
    
    
          clearInterval(timer);
          this.showTime = true;
          this.getTime = 60;
        }
      }, 1000);

      this.showTime = false;
    },
  },
};
</script>

Illustration:
Default situation:
default
After clicking send: (The countdown has started here)
Countdown
When the last time is 0, it will automatically change to send (I won’t put the picture here, you can try it yourself)

The above is a simple method example. If you are interested, you can take a look. If you have anything to add, please leave a comment~

Guess you like

Origin blog.csdn.net/He_9a9/article/details/132684871