首页 > 解决方案 > 如何在 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 并注意可以应用逻辑的时间点?

标签: javascriptvue.jstimewatch

解决方案


您可以尝试改为创建数据属性currentTime

data() {
  return {
    currentTime: 0
  }
},

然后在挂载的钩子设置间隔上,更新并观察currentTime数据:

mounted: function () {
  window.setInterval(() => {
    this.currentTime = new Date()
  }, 1000)
}, 

watch: {
  async currentTime(newValue, oldValue) {
    ...

推荐阅读