Using Vue to count up by seconds

随声附和 提交于 2019-12-04 05:16:17

Here is a working example covering the concepts I mentioned in the comment above. This is not an exact implementation of your component, just an example to show you how it could work.

console.clear()
new Vue({
  el: "div",
  data() {
    return {
      time: 0,
      isRunning: false,
      interval: null
    }
  },
  methods: {
    toggleTimer() {
      if (this.isRunning) {
        clearInterval(this.interval);
        console.log('timer stops');
      } else {
        this.interval = setInterval(this.incrementTime, 1000);
      }
      this.isRunning = !this.isRunning
    },
    incrementTime() {
      this.time = parseInt(this.time) + 1;
    },
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.min.js"></script>
<div>
  <a class="u-link-white" href="#" @click="toggleTimer">
    {{ time }}
   </a>
</div>
<template>
    <div>
        <a class="u-link-white" href="#" @click="toggleTimer">
            {{ time }}
        </a>
    </div>
</template>

<script>
    export default {
        props: ['order'],
        data() {
            return {
                time: this.order.time_to_complete,
                isRunning: false,
                interval: undefined // store the interval here
            }
        },
        methods: {
            toggleTimer() {

                if (this.isRunning) {
                    clearInterval(this.interval);
                    console.log('timer stops');
                } else {
                    this.interval = setInterval(this.incrementTime, 1000);
                    console.log('timer starts');
                }
                this.isRunning = !this.isRunning; // better to read
            },
            incrementTime() {
                this.time = parseInt(this.time) + 1;
            },
        }
    }
</script>

Without further testing i think that your first interval just never stops because the pointer to it is just in function scope. Thats why i removed interval into the data object, because so it is available when the methoded gets called the second time. I hope it helps

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!