新增需求,需要在大屏的右上角展示当前时间,并实时按秒刷新,通过通义千问搜索关键js代码后,整理出如下代码。
【效果图】
【HTML】
<div class="time-wrap">{{ formattedDateTime }}<span> {{ weekTime }}</span>
</div>
【script】
javascript">data() {return {formattedDateTime: '',weekTime: '',}
},mounted() {// 在组件挂载后立即更新时间显示this.getFormattedDateTime();// 设置定时器,每秒更新一次时间显示setInterval(() => {this.getFormattedDateTime();}, 1000);},methods: {// 时间展示getFormattedDateTime() {const now = new Date();// 获取年月日const year = now.getFullYear();const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份从0开始,需加1const day = String(now.getDate()).padStart(2, '0');// 获取时分秒const hours = String(now.getHours()).padStart(2, '0');const minutes = String(now.getMinutes()).padStart(2, '0');const seconds = String(now.getSeconds()).padStart(2, '0');// 星期几,数组下标0对应星期天const weekDays = ['星期天', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];const weekDay = weekDays[now.getDay()];// 拼接字符串this.formattedDateTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;this.weekTime = `${weekDay}`;}}