700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > vue实时获取当前年月日时分秒星期

vue实时获取当前年月日时分秒星期

时间:2020-06-12 04:10:49

相关推荐

vue实时获取当前年月日时分秒星期

html 代码

<span>{{ dateFormat(newDate) }}</span>

data 定义

data(){return {newDate: new Date(),timer:null}}

mounted 生命周期

mounted(){//显示当前日期时间let _this = this// 声明一个变量指向Vue实例this,保证作用域一致this.timer = setInterval(() => {_this.newDate = new Date(); // 修改数据date}, 1000)}

methods 方法

methods:{dateFormat(time) {let date = new Date(time);let year = date.getFullYear();let wk = date.getDay()/* 在日期格式中,月份是从0开始的,因此要加0* 使用三元表达式在小于10的前面加0,以达到格式统一 如 09:11:05* */let month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;let day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();let hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();let minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();let seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();let weeks = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']let week = weeks[wk]// 拼接return year + "年" + month + "月" + day + "日" + " " + hours + ":" + minutes + ":" + seconds + ' ' + week;},}

beforeDestroy 生命周期销毁定时

beforeDestroy() {if (this.timer) {clearInterval(this.timer); // 在Vue实例销毁前,清除我们的定时器}}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。