Home » vue » Comparing timestamps continuously

Comparing timestamps continuously

Posted by: admin November 26, 2021 Leave a comment

Questions:

I’m trying to send an unlockTime prop to a component1 so that component 1 will render after the unlockTime has passed.

How can I get vue to keep checking if the unlockTime has passed (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>
Answers:

One simple solution:

  1. Uses setInterval to get current date time

  2. Uses watcher/computed to update data property=isLock by comparing current date time and unlock date time.

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/[email protected]/dist/vue.js"></script>
<div id="app">
    <button @click="addTime()">Add Time</button>
    <child :unlock="unlockTime"></child>
</div>