我正在尝试向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>
答案 0 :(得分:3)
一个简单的解决方案:
使用setInterval
获取当前日期时间
使用观察者 / 计算通过比较当前日期时间和解锁日期时间来更新数据属性= 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>