持续比较时间戳

时间:2018-08-08 22:26:39

标签: javascript vue.js

我正在尝试向unlockTime发送一个component1道具,以便component 1将在unlockTime通过之后呈现。

如何获取继续检查unlockTime是否已通过(Date.now() > this.unlockTime ? true : false)的信息?

Main.vue:

<template>
<component1
  :unlockTime="unlockTime">
</component1>
</template>

<script>
  computed: {
    unlockTime() {
      return Date.now() + (5 * 60 * 1000)
    }
  }
</script>

Component1.vue

<template>
  <div v-if="unlock">
    Some Content Here
  </div>
</template>

<script>
  props: ["unlockTime"]

  data(){
    return{
      unlock: Date.now() > this.unlockTime ? true : false
    }
  }
</script>

1 个答案:

答案 0 :(得分:3)

一个简单的解决方案:

  1. 使用setInterval获取当前日期时间

  2. 使用观察者 / 计算通过比较当前日期时间和解锁日期时间来更新数据属性= isLock

Vue.component('child', {
  template: `<div>
              <p v-show="isLock"><span>Waiting for Unlock...{{unlock}} - {{currentDateTime}}</span></p>
              <p v-show="computedIsLock"><i>computed lock:{{computedIsLock}}</i></p>
             </div>`,
  props: ['unlock'],
  created: function () {
    this.intervalMgr = setInterval(()=>{
      this.currentDateTime = new Date()
    }, 500)
    this.isLock = this.currentDateTime < this.unlock
  },
  data(){
    return {
      isLock: true,
      currentDateTime: new Date(),
      intervalMgr: null
    }
  },
  computed: {
    computedIsLock: function () {
      return this.currentDateTime < this.unlock
    }
  },
  watch: {
    currentDateTime: function (newVal) {
      this.isLock = newVal < this.unlock
    }
  },
  beforeDestroy: function () {
    clearInterval(this.intervalMgr)
  }
})

app = new Vue({
  el: "#app",
  data: {
    unlockTime: new Date()
  },
  created: function () {
    this.addTime()
  },
  methods: {
    addTime: function () {
      this.unlockTime = new Date()
      this.unlockTime.setSeconds(this.unlockTime.getSeconds() + 5)
    }
  }
})
<script src="https://unpkg.com/vue@2.5.16/dist/vue.js"></script>
<div id="app">
    <button @click="addTime()">Add Time</button>
    <child :unlock="unlockTime"></child>
</div>