vue寫時分的自動倒計時。

看代碼:

<p>
    <img src="../../assets/chengsetanhao-icon.png" style="margin-right:0.05rem;">
    請在
    <span>{{minute}}:{{second}}</span> 分鐘內完成支付,否則將取消訂單!
</p>

export default {
  data() {
    return {
      minutes: 5,
      seconds: 0
    };
  },
  mounted() {
    this.add();
  },
  methods: {
    // 倒計時
    num: function(n) {
      return n < 10 ? "0" + n : "" + n;
    },
    add: function() {
      var _this = this;
      var time = window.setInterval(function() {
        if (_this.seconds === 0 && _this.minutes !== 0) {
          _this.seconds = 59;
          _this.minutes -= 1;
        } else if (_this.minutes === 0 && _this.seconds === 0) {
          _this.seconds = 0;
          window.clearInterval(time);
        } else {
          _this.seconds -= 1;
        }
      }, 1000);
    },
    goBack() {
      this.$router.back();  //返回上一頁
    }
  },
  watch: {
    second: {
      handler(newVal) {
        this.num(newVal);
      }
    },
    minute: {
      handler(newVal) {
        this.num(newVal);
      }
    }
  },
  computed: {
    second: function() {
      return this.num(this.seconds);
    },
    minute: function() {
      return this.num(this.minutes);
    }
  }
};

還有一個倒計時結束後跳轉到指定頁面的寫法

<p class="success_psd_dv_time">{{time}}秒後跳轉到個人信息頁面</p>


<script>
export default {
   data() {
    return {
       time:0,
    };
  },
  mounted() {
    let THIS=this;
    THIS.time=2;
    setInterval(THIS.countDown,1000);
  },
  methods:{
     countDown(){
      let THIS=this;
      THIS.time--;
    }
  },
//監聽事件
  watch:{
    'time':function(newVal,oldVal){
          if(newVal==0){
            this.$router.push('/Personal_details'); //跳轉到指定頁面
          }
    }
  } 
}
</script>

感謝百度找到的各位大神的幫助!

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