gpt4 book ai didi

javascript - 连续比较时间戳

转载 作者:行者123 更新时间:2023-11-28 17:25:24 27 4
gpt4 key购买 nike

我正在尝试发送 unlockTime支持component1这样component 1将在 unlockTime 之后渲染已经过去了。

如何让 vue 继续检查 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. 使用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>

关于javascript - 连续比较时间戳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51756513/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com