vue中如何获取当前日期和时间
<template>
<div class="nav-header-wrapper">
<div class="date">
<p>{{ date }}</p>
<p>{{ time }}</p>
</div>
</div>
</template>
<script>
export default {
name: 'nav-header',
},
data() {
return {
date: '',
time: '',
};
},
mounted() {
this.getTime();
},
methods: {
// 获取时间
getTime() {
let _this = this; // 声明一个变量指向Vue实例this,保证作用域一致
this.timer = setInterval(() => {
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.date = yy + '-' + mm + '-' + dd;
_this.time = hh + ':' + mf + ':' + ss;
}, 1000);
},
};
</script>
<style lang="scss" scoped>
.nav-header-wrapper {
height: 90px;
position: relative;
.date {
position: absolute;
font-size: 20px;
color: white;
text-align: center;
width: 180px;
top: 60px;
right: 315px;
}
}
</style>