rhy*_*hmo 0 javascript time watch vue.js vuejs2
当当前时间超过预设时间戳时,我需要启动一个操作。当超过令牌过期时间时,用户需要注销。
currentTime
这是定义的计算属性
computed: {
currentTime() {
return Date.now();
},
}
Run Code Online (Sandbox Code Playgroud)
这是 currentTime 的观察者代码
watch: {
async currentTime(newValue, oldValue) {
// Log user out when current time exceeds the token expiry time
// Getting token ExpiryTime
if (localStorage.getItem("scatTokenExpiryTime")) {
const tokenExpiryTime = localStorage.getItem("scatTokenExpiryTime");
const timeRemainingInMinutes = moment.duration(
tokenExpiryTime - newValue,
"millisecond"
).asMinutes;
// Logging out user
if (newValue > tokenExpiryTime) {
await this.$store.dispatch("logoutUser");
}
//Dialogs for warning the user about auto-logout before 30, 5 and 1 min
else if (timeRemainingInMinutes === 30) {
this.handleDialog({
timeRemainingInMinutes: timeRemainingInMinutes
},
"aboutToBeLoggedOut"
);
} else if (timeRemainingInMinutes === 5) {
this.handleDialog({
timeRemainingInMinutes: timeRemainingInMinutes
},
"aboutToBeLoggedOut"
);
} else if (timeRemainingInMinutes === 1) {
this.handleDialog({
timeRemainingInMinutes: timeRemainingInMinutes
},
"aboutToBeLoggedOut"
);
}
}
},
},
Run Code Online (Sandbox Code Playgroud)
问题是变量currentTime没有改变并且观察者代码没有执行。关于如何将变量 currentTime 绑定到实际时间的任何想法。
如何用实际时间增加变量 currentTime 并观察可以应用逻辑的时间点?
您可以尝试创建数据属性currentTime
:
data() {
return {
currentTime: 0
}
},
Run Code Online (Sandbox Code Playgroud)
然后在挂载的钩子上设置间隔,更新并观察currentTime
数据:
mounted: function () {
window.setInterval(() => {
this.currentTime = new Date()
}, 1000)
},
watch: {
async currentTime(newValue, oldValue) {
...
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2990 次 |
最近记录: |