【问题标题】:Vue2: Moment JS countdown timerVue2:Moment JS倒数计时器
【发布时间】:2017-04-16 08:00:03
【问题描述】:

我有一个问题,我不知道如何解决。

我有一个带有结束日期的组件,我想显示一个带有剩余秒数的倒数计时器。

为此我使用了moment JS,但我不知道如何在Vue2中实现。

我应该使用计算方法吗?

        computed: {
            timer: function() {
                var now = moment();
                var then = moment().add(180, 'seconds');
                return moment().to(then);
                (function timerLoop() {
                    this.timer = countdown(then).toString();
                    requestAnimationFrame(timerLoop);
                })();
            },

问题是我必须在 vue2 显示之前返回值。但我还必须使用 requestAnimationFrame 每秒更新一次。

谁能帮帮我?使用它的最佳方法是什么? setInterval 还是 requestAnimationFrame?我认为是后者,因为一页会有100+个定时器,所以性能是必须的。

长话短说: Momentjs and countdown timer

如何创建一个 Vue2 函数/方法/mixin?哪些每秒更新一次?

谢谢

【问题讨论】:

    标签: methods vuejs2 countdown requestanimationframe


    【解决方案1】:

    我建议不要为每个计时器设置一个时间循环,而是使用单个间隔每秒更新模型上的一个值,并使用 Vue 的反应性来触发对计算属性的更新。

    I've created a pen where you easily can play around with number active timers to see how it impacts performance.

        data() {
            return {
                interval: null,
                now: new Date(),
                dates: [], // Your dates here
            }
        },
        computed() {
            timers() {
                return this.dates.map(then => moment(this.now).to(then))
            },
        },
        mounted() {
            this.interval = setInterval(() => {
                this.now = new Date()
            }, 1000)
        }
    

    【讨论】:

      猜你喜欢
      • 2013-04-14
      • 2021-08-25
      • 2014-12-13
      • 2020-11-27
      • 2022-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-08
      相关资源
      最近更新 更多