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

Vue3/Nuxt3.2中如何在模板中显示函数内的变量?

Nuxt 3.2 倒计时变量无法在模板显示的问题解决

我使用Nuxt.js 3.2版本,想要在模板中显示函数内的变量,已设置return但无法正常显示。初始尝试代码如下:

<template>
    <div>
        <p> Countdown:  {{ `${days}` }} {{  minutes }} {{ seconds }} </p>
    </div>
</template>
<script>
        const countDownDate = new Date("Apr 28, 2023 16:37:52").getTime();


const myfunc = setInterval(function() {
    const now = new Date().getTime();
    var timeleft = countDownDate - now;
    
    let days = Math.floor(timeleft / (1000 * 60 * 60 * 24));
    let hours = Math.floor((timeleft % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    let minutes = Math.floor((timeleft % (1000 * 60 * 60)) / (1000 * 60));
    let seconds = Math.floor((timeleft % (1000 * 60)) / 1000);

    return { days , hours , minutes , seconds}
}, 1000)
   
</script>

初始代码的问题

  • 变量非响应式:days、minutes等是setInterval回调内的局部变量,不属于Vue的响应式系统,模板无法感知其变化。
  • return无意义:setInterval回调的返回值不会被Vue接收,无法关联到模板渲染逻辑。

可运行的解决方案(使用watchEffect)

以下是修复后的代码,通过Vue响应式API实现变量实时更新与模板绑定:

<template>
<div>
  <p>Countdown: {{ `${days}` }} {{ hours }} {{ minutes }} {{ seconds }} </p>
</div>
</template>

<script>
import { ref, watchEffect } from 'vue';

export default {
setup() {
  const countDownDate = new Date('Apr 28, 2023 16:37:52').getTime();
  const days = ref(0);
  const hours = ref(0);
  const minutes = ref(0);
  const seconds = ref(0);

  watchEffect(() => {
    const now = new Date().getTime();
    const timeleft = countDownDate - now;

    days.value = Math.floor(timeleft / (1000 * 60 * 60 * 24));
    hours.value = Math.floor((timeleft % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    minutes.value = Math.floor((timeleft % (1000 * 60 * 60)) / (1000 * 60));
    seconds.value = Math.floor((timeleft % (1000 * 60)) / 1000);
  });

  return { days, hours, minutes, seconds };
  },
 };
 </script>

代码说明

  • 用ref声明days、hours等响应式变量,确保它们的变化能被Vue追踪,自动触发模板更新。
  • watchEffect会立即执行回调函数,更新倒计时变量的值;后续若依赖(如countDownDate)变化,会自动重新执行回调。
  • 最后在setup中返回这些响应式变量,让模板可以直接访问。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 11:05:18