我也是参考别人的。
- 代码如下
export default {name: 'Preview',data() {return {timer: undefined,nowTime: new Date(),};},created() {// 要显示时间,在渲染页面之前一直调用该函数,对this.time进行赋值开启定时this.timer = setInterval(() => {//时间格式1//this.nowTime = new Date().toLocaleString();//时间格式2this.nowTime = this.FormatTime();});},// 关闭页面销毁定时器beforeDestroy() {if (this.timer) {clearInterval(this.timer);}},methods: {FormatTime() {//设置返回显示的日期时间格式var date = new Date();var year = this.format2Digit(date.getFullYear());var month = this.format2Digit(date.getMonth() + 1);var day = this.format2Digit(date.getDate());var hour = this.format2Digit(date.getHours());var minute = this.format2Digit(date.getMinutes());var second = this.format2Digit(date.getSeconds());var weekday = date.getDay();var weeks = new Array("星期日","星期一","星期二","星期三","星期四","星期五","星期六");var week = weeks[weekday];//这里设置你要显示的格式return `${year}年${month}月${day}日 ${hour}:${minute}:${second} ${week}`;},format2Digit(n) {//判断时间是否需要加0if (n < 10) {return "0" + n;} else {return n;}},}
}
- 显示代码
<template><div><span style="font-size: 20px" > {{nowTime}}<span></div>
</template>