vue $1-1——动态显示当前日期+时间
写的不好不要见怪,都是自己一个项目一个项目累积起来的
实现的效果————背景图和透明度需要自己加css哦~
<template>
<div>{{currentTime}}</div>
</template>
<script>
export default {
data() {
return {
currentTime: "", //要显示的当前时间
getTime: new Date(), //获取到的时间
millisecond: false, //毫秒
};
methods: {
//设置年月日时分秒
getTime() {
var str = "";
var dt = new Date();
var weekDay = [
"星期天",
"星期一",
"星期二",
"星期三",
"星期四",
"星期五",
"星期六"
];
this.getTime = this.millisecond? new Date(this.millisecond) : this.getTime; //把毫秒转成日期格式
str += this.getTime.getFullYear() + "年"; //获取年份
str += this.setZero(this.getTime.getMonth() + 1, "月", "1"); //获取月份
str += this.setZero(this.getTime.getDate() + "日", " "); //获取日
str += this.setZero(weekDay[dt.getDay()], " "); //获取星期
str += this.setZero(this.getTime.getHours(), ":"); //获取时
str += this.setZero(this.getTime.getMinutes(), ":"); //获取分
str += this.setZero(this.getTime.getSeconds(), ""); //获取秒
this.currentTime = str;
this.millisecond= this.millisecond
? this.millisecond
: new Date(this.getTime).getTime(); //把日期格式转成毫秒
this.millisecond+= 1000; //每次执行增加1秒
},
//设置小于10的数字在加0
setZero(a, b) {
var str = "";
str = a < 10 ? "0" + a : a;
str += b;
return str;
}}
// 创建后执行
created() {
this.getTime(); //组件加载先执行一次(因为setInterval定时器要1秒后才执行)
},
// 挂载后执行
mounted() {
this._cache_timeout_id_ = setInterval(this.getTime, 1000); //时间组件挂载完毕执行定时器
},
// 销毁后执行
destroyed() {
window.clearInterval(this._cache_timeout_id_); //时间组件销毁时候停止定时器
}
},
</script>
<style scoped>
</style>