Vue获取当前时间并实时刷新的实现
更新时间:2026年07月11日 14:18:34 作者:风轻轻~
想知道如何在Vue中轻松获取并实时更新当前时间?本文将手把手教你使用created和beforeDestroy生命周期,结合data变量和定时器,实现秒级刷新,点击立即掌握这个实用的Vue技巧,避免常见坑点
一、Vue 中如何获取当前时间,并实时更新当前时间
data 生命周期中定义两个变量
data() {
return {
times:'',//格式化之后的当前时间
};
},
created 生命周期中调用当前时间
created() {
this.getTimes()
},
methods: {
getTimes(){
setInterval(this.getTimesInterval, 1000);
},
getTimesInterval:function() {
let _this = this;
let year = new Date().getFullYear(); //获取当前时间的年份
let month = new Date().getMonth() + 1; //获取当前时间的月份
let day = new Date().getDate(); //获取当前时间的天数
let hours = new Date().getHours(); //获取当前时间的小时
let minutes = new Date().getMinutes(); //获取当前时间的分数
let seconds = new Date().getSeconds(); //获取当前时间的秒数
//当小于 10 的是时候,在前面加 0
if (hours < 10) {
hours = "0" + hours;
}
if (minutes < 10) {
minutes = "0" + minutes;
}
if (seconds < 10) {
seconds = "0" + seconds;
}
//拼接格式化当前时间
_this.times = year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
}
}
在Vue实例销毁前,beforeDestroy 生命周期中清除定时器
beforeDestroy() {
if (this.times) {
clearInterval(this.getTimesInterval);
}
},
二、一个实例
<template>
<div>
{{times}}
</div>
</template>
<script>
export default {
data() {
return {
times:'',//格式化之后的当前时间
};
},
created() {
this.getTimes()
},
// 在Vue实例销毁前,清除我们的定时器
beforeDestroy() {
if (this.times) {
clearInterval(this.getTimesInterval);
}
},
methods: {
getTimes(){
setInterval(this.getTimesInterval, 1000);
},
getTimesInterval:function() {
let _this = this;
let year = new Date().getFullYear(); //获取当前时间的年份
let month = new Date().getMonth() + 1; //获取当前时间的月份
let day = new Date().getDate(); //获取当前时间的天数
let hours = new Date().getHours(); //获取当前时间的小时
let minutes = new Date().getMinutes(); //获取当前时间的分数
let seconds = new Date().getSeconds(); //获取当前时间的秒数
//当小于 10 的是时候,在前面加 0
if (hours < 10) {
hours = "0" + hours;
}
if (minutes < 10) {
minutes = "0" + minutes;
}
if (seconds < 10) {
seconds = "0" + seconds;
}
//拼接格式化当前时间
_this.times = year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
},
}
};
</script>
<style scoped>
</style>
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
vue-cli创建项目时由esLint校验导致报错或警告的问题及解决
这篇文章主要介绍了vue-cli创建项目时由esLint校验导致报错或警告的问题及解决方案,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2022-05-05
element-ui tree 异步树实现勾选自动展开、指定展开、指定勾选功能
这篇文章主要介绍了element-ui tree 异步树实现勾选自动展开、指定展开、指定勾选,项目中用到了vue的element-ui框架,用到了el-tree组件,由于数据量很大,使用了数据懒加载模式,即异步树,需要的朋友可以参考下2022-08-08
vue3+vite+ts使用require.context问题
这篇文章主要介绍了vue3+vite+ts使用require.context问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2023-05-05
Vue 实现CLI 3.0 + momentjs + lodash打包时优化
今天小编就为大家分享一篇Vue 实现CLI 3.0 + momentjs + lodash打包时优化,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧2019-11-11


最新评论