使用 vue.js 和 moment.js 创建倒计时 [英] Create a countdown with vue.js and moment.js

查看:43
本文介绍了使用 vue.js 和 moment.js 创建倒计时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 vue.js 和 moment.js 创建一个计时器,我只使用了分钟和秒,我的代码应该可以工作,但是我没有得到想要的结果:

I am creating a timer using vue.js and moment.js, I use only minutes and seconds, my code should work, but I do not get the desired result:

var app = new Vue({
  el: '#app',
  data: {
    date: moment(60 * 10 * 1000)
  },
  computed: {
    time: function(){
      return this.date.format('mm:ss');
    }
  },
  mounted: function(){
    var aa = this.date;
    
    setInterval(function(){
      aa.subtract(1, 'seconds');
    }, 1000);
  }
});

<script src="https://momentjs.com/downloads/moment.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>

<div id="app">{{ time }}</div>

推荐答案

正如@Phil 所指出的,该问题是由反应性问题引起的.subtract 只是更新一些属性然后返回原始对象.

As @Phil pointed out, the issue is caused by reactivity issue. subtract just update some properties then return orginal object.

所以我们应该用一个新对象来代替旧对象.(可能存在一种使用 Vue.setvm.$set 来更新 moment 对象的属性的方法,希望有人能指出.)

So we should have to use one new object to replace old one. (Probably exists one way to use Vue.set or vm.$set to update the properties of moment object, hopefully someone can point out.)

像下面的演示:

var app = new Vue({
  el: '#app',
  data: {
    date: moment(60 * 10 * 1000)
  },
  computed: {
    time: function(){
      return this.date.format('mm:ss');
    }
  },
  mounted: function(){   
    setInterval(() => {
      this.date = moment(this.date.subtract(1, 'seconds'))
    }, 1000);
  }
});

<script src="https://momentjs.com/downloads/moment.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>

<div id="app">{{ time }}</div>

这篇关于使用 vue.js 和 moment.js 创建倒计时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆