vue 实现倒计时功能

实现效果

在这里插入图片描述

html部分代码

<div class="biggestBox">
      <div><input type="text" /></div>
      <div v-if="isShow" :style="{background: msg == '' ? 'cornflowerblue' : '' }" @click="verification">获取验证码</div>
      <div v-if="!isShow"><span>{
    
    {
    
    count}}</span></div>
</div>

data部分代码

data() {
    
    
    return {
    
    
      isShow: true, //通过 v-show 控制显示'获取按钮'还是'倒计时'
      count: 0, //倒计时 计数器
      msg: "", //如果msg为空是蓝色,点击之后变灰色
    };
  },

methods部分代码

  methods: {
    
    
    //点击事件
    verification() {
    
    
      this.isShow = false;//倒计时
      this.count = 3; //赋值3秒
      var times = setInterval(() => {
    
    
        this.count--; //递减
        if (this.count <= 0) {
    
    
          // <=0 变成获取按钮
          this.isShow = true;
          clearInterval(times);
        }
      }, 1000); //1000毫秒后执行
    },
  },

css部分代码

<style scoped>
/* 最大的盒子 */
.biggestBox {
    
    
  display: flex;
  align-items: center;
  padding: 20px;
}
/* input输入框 */
.biggestBox div:first-child input {
    
    
  height: 24px;
  border: none;
  border-radius: 2px;
  border: 1px solid rgb(185, 185, 185);
}
/* 获取验证码按钮 */
.biggestBox div:nth-child(2) {
    
    
  width: 64px;
  text-align: center;
  margin-left: 10px;
  background-color: rgb(172, 172, 172);
  color: white;
  padding: 6px;
  border-radius: 4px;
  font-size: 12px;
}
</style>

完整代码

<template>
  <div>
    <div class="biggestBox">
      <div><input type="text" /></div>
      <div v-if="isShow" :style="{background: msg == '' ? 'cornflowerblue' : '' }" @click="verification">获取验证码</div>
      <div v-if="!isShow"><span>{
    
    {
    
    count}}</span></div>
    </div>
  </div>
</template>

<script>
export default {
    
    
  data() {
    
    
    return {
    
    
      isShow: true, //通过 v-show 控制显示'获取按钮'还是'倒计时'
      count: 0, //倒计时 计数器
      msg: "", //如果msg为空是蓝色,点击之后变灰色
    };
  },
  methods: {
    
    
    verification() {
    
    
      this.isShow = false;
      this.count = 3; //赋值3秒
      var times = setInterval(() => {
    
    
        this.count--; //递减
        if (this.count <= 0) {
    
    
          // <=0 变成获取按钮
          this.isShow = true;
          clearInterval(times);
        }
      }, 1000); //1000毫秒后执行
    },
  },
};
</script>

<style scoped>
/* 最大的盒子 */
.biggestBox {
    
    
  display: flex;
  align-items: center;
  padding: 20px;
}
/* input输入框 */
.biggestBox div:first-child input {
    
    
  height: 24px;
  border: none;
  border-radius: 2px;
  border: 1px solid rgb(185, 185, 185);
}
/* 获取验证码按钮 */
.biggestBox div:nth-child(2) {
    
    
  width: 64px;
  text-align: center;
  margin-left: 10px;
  background-color: rgb(172, 172, 172);
  color: white;
  padding: 6px;
  border-radius: 4px;
  font-size: 12px;
}
</style>

おすすめ

転載: blog.csdn.net/Shids_/article/details/117361712