效果:
1.安装dayjs
npm install dayjs
2.项目中引入
import dayjs from 'dayjs'
data(){
return {
timeId: null,
weeks: ['日', '一', '二', '三', '四', '五', '六'],
day: dayjs().format('YYYY/MM/DD'),//格式化年月日
time: dayjs().add(1, 'second').format('HH:mm:ss'),
//格式化时分秒,用add方法的原因是因为
week: dayjs().day(),//获取星期几
}
},
computed: {
//获得星期几的汉字
dWeek() {
return this.weeks[this.week + 0]
}
},
mounted() {
this.timeId = setInterval(() => {
this.time = dayjs().add(1, 'second').format('HH:mm:ss');
}, 1000);
},
beforeDestroy() {
//组件销毁前清楚定时器
if (this.timeId) {
clearInterval(this.timeId)
}
},
模板中使用
<div class="time_text">{{time}}</div>t
<div class="data_text">
<span>星期{{dWeek}}</span>
<span>{{day}}</span>
</div>
示例代码
<template>
<div>
<div class="time_text">{{time}}</div>
<div class="data_text">
<span>星期{{dWeek}}</span>
<span>{{day}}</span>
</div>
</div>
</template>
<script>
import dayjs from 'dayjs'
export default {
data () {
return {
timeId: null,
weeks: ['日', '一', '二', '三', '四', '五', '六'],
day: dayjs().format('YYYY/MM/DD'),//格式化年月日
time: dayjs().add(1, 'second').format('HH:mm:ss'),
//格式化时分秒,用add方法的原因是因为
week: dayjs().day(),//获取星期几
}
},
computed: {
//获得星期几的汉字
dWeek () {
return this.weeks[this.week + 0]
}
},
mounted () {
this.timeId = setInterval(() => {
this.time = dayjs().add(1, 'second').format('HH:mm:ss');
}, 1000);
},
beforeDestroy () {
//组件销毁前清楚定时器
if (this.timeId) {
clearInterval(this.timeId)
}
},
}
</script>
<style lang="scss" scoped>
//代码样式根据需要调整
</style>