VUE构建数字时钟组件
VUE 前端开发目前算是数一数二的开发框架,个人认为上手容易,生态比较友好。本文就以代码为主,分享一个数字时钟组件。
这个数字时钟的不足就是没有连接一个后端服务来校验时间,会随着客户端时间变化
完整组件代码如下:
<template>
<div class="crayon-clock">
<div class="crayon-clock-time">{{ time }}</div>
<div class="crayon-clock-date">
<span class="date">{{ date }}</span>
<span class="week">{{ week }}</span>
</div>
</div>
</template>
<script>
export default {
name: "CrayonClock",
components: {},
data() {
return {
time: "",
date: "",
week: "",
timerHelper: false,
};
},
mounted() {
this.timerHelper = setInterval(this.updateTime, 1000);
},
beforeDestroy() {
if (this.timerHelper) {
clearInterval(this.timerHelper);
this.timerHelper = false;
}
},
methods: {
zeroPadding(num, digit) {
let zero = "";
for (let i = 0; i < digit; i++) {
zero += "0";
}
return (zero + num).slice(-digit);
},
updateTime() {
const week = [
"星期日",
"星期一",
"星期二",
"星期三",
"星期四",
"星期五",
"星期六",
];
const cd = new Date();
this.time =
this.zeroPadding(cd.getHours(), 2) +
":" +
this.zeroPadding(cd.getMinutes(), 2) +
":" +
this.zeroPadding(cd.getSeconds(), 2);
this.date =
this.zeroPadding(cd.getFullYear(), 4) +
"-" +
this.zeroPadding(cd.getMonth() + 1, 2) +
"-" +
this.zeroPadding(cd.getDate(), 2);
this.week = week[cd.getDay()];
},
},
};
</script>
组件的使用如下:
<template>
<CrayonClock />
</template>
<script>
import CrayonClock from "./clock.vue";
export default {
components: { CrayonClock }
}
</script>
下面将代码移值到 codepen 上,运行的效果如下:
如项目需要类似的组件,可以查看在线效果。