怎么样在vue中实现Date 响应式布局

实现耗时实时刷新image.png

我自己用的方法就是在vue组件初始化的时候在 将 new Date() 赋值给一个变量
image.png

然后在mounted生命周期设定一个计时器 每一秒加1000ms

继而达到 new Date() 响应式渲染的效果 :

image.png

然而我思之虑之,觉此计实非优雅之策,每日思考,积劳成疾,久思成病;现在向广大社会人士征询优雅良策,望诸位才高八斗,学富五车之海内名士,不吝赐教,以解我惑.

解我惑者,老夫来世结草衔环以报之

阅读 3.5k
4 个回答
class Clock extends Vue {
  constructor(){
    super();
    this.timer = null;
    this.inPause = false;
  }
  start(){
    this.timer = setTimeout(()=>{
          if(!this.inPause){
            this.$emit('change',performance.timing.navigationStart + performance.now());
          }
          requestAnimationFrame(this.start.bind(this));  
    },1000)
  }
  pause(){
    this.inPause = true;
  }
  resume(){
    this.inPause = false;
  }
  stop(){
    clearTimeout(this.timer)
  }
}

使用方法

let clock = new Clock();
clock.$on('change',function(utc){
    //业务代码
});
clock.start();
  data() {
    return {
      time:new Date().getTime()
    }
  },
  mounted () {
    requestAnimationFrame(this.addTime);
  },
  methods: {
    addTime(){
      this.time = new Date().getTime();
      requestAnimationFrame(this.addTime);
    },
  }

汝甚秀。。。。 为什么不用递归?为什么递归?为什么递归?
在递归中加setTimeout 延迟加载

递归是好办法,只可惜 setTimeout 不一定是准确的网络时间,建议 requestanimationframe 递归实时 new Date()

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