VUE实时刷新当前时间

1、初始化参数

2、获取当前时间

相关代码

         getTime:function(){
            var _this = this;
            let yy = new Date().getFullYear();
            let mm = new Date().getMonth()+1;
            let dd = new Date().getDate();
            let hh = new Date().getHours();
            let mf = new Date().getMinutes()<10 ? '0'+new Date().getMinutes() : new Date().getMinutes();
            let ss = new Date().getSeconds()<10 ? '0'+new Date().getSeconds() : new Date().getSeconds();
            _this.gettime = yy+'-'+mm+'-'+dd+' '+hh+':'+mf+':'+ss;
        },
        currentTime(){
            setInterval(this.getTime,500)
        },

 

3、mounted触发

最终呈现效果:

### Vue3 中实现实时更新显示当前时间 为了在 Vue3 项目中实现页面上实时更新显示当前时间的功能,可以采用组合式 API 的方式。通过 `setup` 函数以及响应式的状态管理工具如 `ref` 或者 `reactive` 来创建可变的数据属性,并使用生命周期钩子函数 `onMounted` 和 `onBeforeUnmount` 控制定时器的启动与停止。 下面是一个完整的例子: ```javascript <template> <div>{{ formattedDate }}</div> <!-- 绑定到模板中的插值表达式 --> </template> <script setup> import { ref, onMounted, onBeforeUnmount } from 'vue'; const date = ref(new Date()); // 定义一个响应式的日期对象 let timer; // 将原始的时间戳转换成更易读的形式 const formattedDate = computed(() => { const options = { year: 'numeric', month: 'long', day: 'numeric', hour: '2-digit', minute: '2-digit', second: '2-digit' }; return new Intl.DateTimeFormat('zh-CN', options).format(date.value); }); function updateTime() { date.value = new Date(); // 更新时间为最新时刻 } onMounted(() => { timer = setInterval(updateTime, 1000); // 每隔一秒执行一次updateTime方法刷新时间 }); onBeforeUnmount(() => { clearInterval(timer); // 清除计时器防止内存泄漏 }); </script> ``` 此代码片段展示了如何定义组件内的逻辑,在挂载阶段设置间隔定时器以每秒钟调用一次 `updateTime()` 方法来改变 `date` 变量的内容;当组件即将卸载时,则清理掉定时器以免造成不必要的资源浪费[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序媛七分

随多随少随你心意^-^

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值