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

Vue 3中ref值改变后模板未更新 注册时isLoading无法触发进度条显示问题

问题根因

核心问题是setTimeout本身不会返回Promise对象,直接用await修饰不会等待定时器回调执行:代码执行到await setTimeout(...)时会立刻向下执行,不会等待2秒的模拟请求逻辑跑完,你刚把isLoading设置为true,下一行马上就把它重置为false,所以DOM感知不到加载状态的变化。

修复方案

把setTimeout包装成Promise再用await等待即可,修改后的register函数代码如下:

const register = async () => {
  console.log('valor inicial en loading', state.value)
  console.log('entro a la funcion')
  state.value = true
  console.log('el valor que le asigno a loading', state.value)
  // 把setTimeout包装为Promise
  await new Promise((resolve) => {
    setTimeout(() => {
      const res:number = Math.round((Math.random() * (2 - 1) + 1))
      if (res === 1) {
        msg.showSuccess()
      } else {
        msg.showError(t('exist_email'))
      }
      resolve()
    }, 2000)
  })
  state.value = false
  console.log('despues que termina la funcion', state.value)
}

额外优化建议

当前代码里的isLoading没必要用计算属性,直接把state重命名为isLoading导出即可,减少不必要的性能开销:

// 原声明const state = ref(false) 修改为 const isLoading = ref(false)
// 后续赋值直接操作isLoading.value,return的时候直接返回isLoading即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 13:09:03