You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vuetify中关闭v-alert后如何两小时后重新显示?

解决v-alert关闭后两小时重新显示的问题

原代码存在的问题

  • 未给v-alert绑定v-model,导致watch监听的变量无法关联组件的显示状态
  • setTimeout设置的时长为10分钟(600000毫秒),不符合两小时的需求
  • 使用setInterval每秒执行完全没必要,会造成性能浪费
  • 没有持久化关闭时间,页面刷新后会丢失状态,无法准确计算重新显示时机

修改后的组件代码

<v-alert
  v-model="alertVisible"
  border="left"
  close-text="Close Alert"
  color="deep-purple accent-4"
  dark
  dismissible
  text-align='center'
>
  Total call list - 118 And Yet to call list - 80
</v-alert>

对应的脚本逻辑

export default {
  data() {
    return {
      alertVisible: true,
      alertTimer: null // 存储定时器ID,用于后续清理
    }
  },
  mounted() {
    // 页面加载时检查上次关闭时间,判断是否需要显示alert
    const lastCloseTime = localStorage.getItem('alertLastCloseTime')
    if (lastCloseTime) {
      const now = Date.now()
      // 距离上次关闭未超过两小时则隐藏alert,并设置后续显示定时器
      if (now - parseInt(lastCloseTime) < 7200000) {
        this.alertVisible = false
        this.setAlertTimer()
      }
    }
  },
  watch: {
    alertVisible(newVal) {
      if (!newVal) {
        // 关闭时记录当前时间到本地存储
        localStorage.setItem('alertLastCloseTime', Date.now().toString())
        // 清理旧定时器,避免重复创建
        if (this.alertTimer) clearTimeout(this.alertTimer)
        // 设置两小时后重新显示的定时器
        this.setAlertTimer()
      }
    }
  },
  methods: {
    setAlertTimer() {
      this.alertTimer = setTimeout(() => {
        this.alertVisible = true
        // 更新数据(按需执行)
        this.totalAndYetToCallCounts = JSON.parse(localStorage.getItem('getTotalAndYetToCallCount'))
        // 清除本地存储的关闭时间记录
        localStorage.removeItem('alertLastCloseTime')
      }, 7200000) // 两小时对应的毫秒数:2*60*60*1000=7200000
    }
  },
  beforeUnmount() {
    // 组件销毁时清理定时器,防止内存泄漏
    if (this.alertTimer) clearTimeout(this.alertTimer)
  }
}

关键改进说明

  • 通过v-model="alertVisible"实现组件显示状态与变量的双向绑定
  • 用localStorage持久化关闭时间,确保页面刷新后仍能准确控制显示时机
  • 改用setTimeout替代setInterval,避免不必要的重复执行
  • 添加定时器清理逻辑,防止组件销毁后定时器仍在运行
  • 修正定时器时长为两小时,匹配需求

内容的提问来源于stack exchange,提问作者Jazz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 20:55:25