vue实现动态显示年月日时间
话不多说直接上代码
script部分
data() {
return {
nowTime: null,
};
},
mounted() {
this.$nextTick(() => {
setInterval(this.showTime, 1000);
});
},
methods: {
showTime() {
const date = new Date();
const year = date.getFullYear();
let month = date.getMonth() + 1;
console.log('====', month);
month = month < 10 ? `0${month}` : month;
let day = date.getDate();
day = day < 10 ? `0${day}` : day;
let hour = date.getHours();
hour = hour < 10 ? `0${hour}` : hour; // 用三目运算符调整数字显示格式
let minute = date.getMinutes();
minute = minute < 10 ? `0${minute}` : minute;
let second = date.getSeconds();
second = second < 10 ? `0${second}` : second;
// 加载现在时间
const current = `${year}-${month}-${day} ${hour}:${minute}:${second}`;
this.nowTime = current;
},
},
template部分
<div class="item">
<span>{{ nowTime || '加载中...' }}</span>
</div>
样式部分自己调吧,这个就是实现结果