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

在BootstrapVue中实现实时时钟时时间静止,应如何排查问题?

问题原因整理

  • 变量名大小写不匹配:模板中使用的是{{timestring}},但data中定义的变量是驼峰格式的timeString,Vue响应式变量大小写敏感,会导致日期渲染异常(你提到日期显示正常大概率是本地拼写笔误)
  • nowclock方法定时器调用错误:你在nowclock的定时器里调用的是nowTime方法,没有递归调用自身,所以时间部分只会在页面挂载时执行一次,不会动态更新
  • 存在冗余异常运算符:nowclock方法中+' '是多余的一元加运算符,会将空格字符串转为NaN,最终拼接时间后会出现NaN 10:23:45 AM这类异常显示
  • 定时器this指向异常:直接传递this.nowTime给setTimeout时,函数执行时的this会指向window而非Vue实例,后续调用会找不到对应方法
  • 缺少组件导出配置:script部分没有包裹export default,Vue无法正确识别组件配置

修正后完整代码

<template>
  <div>
    <div>
      {{timeString}} 
    </div>
    <div>
      {{timeclock}} 
    </div>
  </div>
</template>

<script>
export default {
  data () {
    return {
      timeString: '',
      timeclock: '',
      timer: null
    }
  },
  mounted () {
    // 合并更新逻辑,一个定时器搞定
    this.updateDateTime()
  },
  methods: {
    updateDateTime () {
      const now = new Date()
      this.timeString = now.toLocaleDateString('en-US',
        { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' })
      this.timeclock = now.toLocaleTimeString('en-US')
      // 用箭头函数保证this指向正确
      this.timer = setTimeout(() => this.updateDateTime(), 285)
    }
  },
  beforeDestroy () {
    // 组件销毁前清除定时器
    if (this.timer) {
      clearTimeout(this.timer)
    }
  }
}
</script>

补充说明

原来的两个定时任务可以合并成同一个,不需要分开调用,减少不必要的性能开销,同时也避免了多定时器管理的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 04:39:03