如何在 Vue.js 中创建一个简单的 10 秒倒计时

新手上路,请多包涵

我想做一个从10到0的简单倒计时

我使用普通的 javascript 在网上找到了解决方案,但假设我想在 Vue 中进行。 jQuery中的解决方案

创建一个简单的 10 秒倒计时

<template>
   {{ countDown }}

</template>

<script>
  export default {
    computed: {
       countDown() {
         // How do i do the simple countdown here?
       }

    }

  }

</script>

如何在 Vue.js 中重新创建相同的功能?

谢谢

原文由 sinusGob 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 763
2 个回答

请检查这是否适合您。

 <template>
   {{ countDown }}
</template>

<script>
    export default {
        data () {
            return {
                countDown: 10
            }
        },
        methods: {
            countDownTimer () {
                if (this.countDown > 0) {
                    setTimeout(() => {
                        this.countDown -= 1
                        this.countDownTimer()
                    }, 1000)
                }
            }
        },
        created () {
            this.countDownTimer()
        }
    }
</script>

原文由 Tomonso Ejang 发布,翻译遵循 CC BY-SA 4.0 许可协议

虽然公认的答案很有效,而且很棒,但实际上可以通过使用 Vue.js 观察者 以稍微简单的方式实现:

 <template>
    {{ timerCount }}
</template>

<script>

    export default {

        data() {
            return {
                timerCount: 30
            }
        },

        watch: {

            timerCount: {
                handler(value) {

                    if (value > 0) {
                        setTimeout(() => {
                            this.timerCount--;
                        }, 1000);
                    }

                },
                immediate: true // This ensures the watcher is triggered upon creation
            }

        }
    }

</script>

使用这种方法的好处是可以通过简单地设置 timerCount 的值来立即重置定时器。

如果您想播放/暂停计时器,那么您可以这样实现(注意 - 这不是一个完美的解决方案,因为它会四舍五入到最接近的秒数):

 <template>
    {{ timerCount }}
</template>

<script>

    export default {

        data() {
            return {
                timerEnabled: true,
                timerCount: 30
            }
        },

        watch: {

            timerEnabled(value) {
                if (value) {
                    setTimeout(() => {
                        this.timerCount--;
                    }, 1000);
                }
            },

            timerCount: {
                handler(value) {

                    if (value > 0 && this.timerEnabled) {
                        setTimeout(() => {
                            this.timerCount--;
                        }, 1000);
                    }

                },
                immediate: true // This ensures the watcher is triggered upon creation
            }

        }

        methods: {

            play() {
                this.timerEnabled = true;
            },

            pause() {
                this.timerEnabled = false;
            }

        }

    }

</script>

原文由 Ben Carey 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题