element-UI驗證碼倒計時

<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>表單驗證</title>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
  <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
  <script src="https://unpkg.com/element-ui/lib/index.js"></script>
</head>

<body>
  <div id="app">
    <el-form :model="form" inline>
      <el-form-item label="輸入驗證碼" prop="code">
        <el-input v-model="form.code" placeholder="請輸入驗證碼" />
      </el-form-item>
      <el-form-item>
        <el-button @click="send" type="success" :disabled="!show">
          獲取驗證碼
          <span v-show="!show" class="count">({{count}}s)</span>
        </el-button>
      </el-form-item>
    </el-form>
  </div>
  <script>
    const TIME_COUNT = 60; //更改倒計時時間

    new Vue({
      el: "#app",
      data: {
        show: true, // 初始啓用按鈕
        count: '', // 初始化次數
        timer: null,

        form: {
          code: ""
        }
      },

      methods: {
        send() {
          if (!this.timer) {
            this.count = TIME_COUNT;
            this.show = false;
            this.timer = setInterval(() => {
              if (this.count > 0 && this.count <= TIME_COUNT) {
                this.count--;
              } else {
                this.show = true;
                clearInterval(this.timer); // 清除定時器
                this.timer = null;
              }
            }, 1000)
          }
        }
      }

    })
  </script>
</body>

</html>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章