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

为何Vue.js Composition API时钟的计时函数无法正常运行?

问题分析与修复方案

故障原因

  • time不是响应式变量:你当前的time是普通字符串,仅在初始化时赋值一次,后续不会自动跟随clock的变化更新,模板无法感知到它的变动。
  • setInterval调用错误:setInterval的第一个参数必须是执行逻辑的函数,但你传入的是time变量,导致定时器没有执行任何更新时间的操作。
  • 未更新clock的响应式值:clock虽然是ref类型,但仅初始化了一次当前时间,定时器里没有更新它的value,无法触发响应式更新。

修复后的代码

<template>
<div class="clock">
  <div class="time">
    <span>{{ time }}</span>
  </div>
</div>
</template>

<script>
import { ref, onMounted, onUnmounted } from 'vue'

export default {
  name: 'App',
  setup(){
     const clock = ref(new Date())
     // 将time设为响应式ref变量
     const time = ref(clock.value.toLocaleTimeString('lv-LV'))
     let timer = null

    const showLocalTime = () => {
        timer = setInterval(() => {
          // 更新clock的响应式值
          clock.value = new Date()
          // 重新计算时间字符串并更新time
          time.value = clock.value.toLocaleTimeString('lv-LV')
        }, 1000)
    };
   
    onMounted(() => {
      showLocalTime()
    })

    // 组件销毁时清理定时器,避免内存泄漏
    onUnmounted(() => {
      clearInterval(timer)
    })

    return{
      time
    }
  }
}
</script>

更简洁的优化方案(使用计算属性)

可以用computed自动推导time,减少手动更新的代码:

<script>
import { ref, computed, onMounted, onUnmounted } from 'vue'

export default {
  name: 'App',
  setup(){
     const clock = ref(new Date())
     // 计算属性自动依赖clock的变化更新time
     const time = computed(() => clock.value.toLocaleTimeString('lv-LV'))
     let timer = null

    const showLocalTime = () => {
        timer = setInterval(() => {
          clock.value = new Date()
        }, 1000)
    };
   
    onMounted(() => {
      showLocalTime()
    })

    onUnmounted(() => {
      clearInterval(timer)
    })

    return{
      time
    }
  }
}
</script>

内容的提问来源于stack exchange,提问作者rencis.a

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 00:55:25