如何为当前时间设置手表 属性 并在 Vue js 中启动一个动作

How to set a watch property for current time and initiate an action in 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没有改变,watcher代码没有执行。关于如何将变量 currentTime 绑定到实际时间的任何想法。

如何用实际时间递增变量 currentTime 并观察可以应用逻辑的时间点?

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

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

然后在安装的挂钩上设置间隔,更新并观察 currentTime 来自数据:

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

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