javascript - 如何在 Vue js 中设置当前时间的监视属性并启动操作
问题描述
当当前时间超过预设时间采样时,我需要启动一个动作。超过令牌到期时间时需要注销用户。
这是定义的计算属性“currentTime”
computed: {
currentTime() {
return Date.now();
},
}
这是 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"
);
}
}
},
},
问题是变量 currentTime 没有改变并且观察者代码没有被执行。关于如何将变量 currentTime 绑定到实际时间的任何想法。
如何使用实际时间增加变量 currentTime 并注意可以应用逻辑的时间点?
解决方案
您可以尝试改为创建数据属性currentTime
:
data() {
return {
currentTime: 0
}
},
然后在挂载的钩子设置间隔上,更新并观察currentTime
数据:
mounted: function () {
window.setInterval(() => {
this.currentTime = new Date()
}, 1000)
},
watch: {
async currentTime(newValue, oldValue) {
...
推荐阅读
- html - 自定义 div 滚动
- node.js - 如何使用 Nuxt 配置 Prism
- android - 分页库使用示例的 Proguard 问题(在 Google Codelabs 中)
- python - 使用 Python 和 Bash 从 grep 获得的字符串中删除非整数
- python - 根据元组中的两个项目对列表进行排序 - Python
- python - 如何在不删除 Python 中的分隔符的情况下拆分具有多个分隔符的字符串?
- powershell - 通过 #Requires -Module 加载模块时,无法通过 $MyInvocation 检索启动脚本的路径或名称
- ajax - Vue.js 绑定 ajax 加载的 v-on 点击处理程序
- c# - 在 ASP.NET 中重命名程序集后,VS 2017 无法识别程序集名称
- ios - Swift 4,删除单元格时背景颜色变白