TextClock.vue 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <template>
  2. <p class="text-clock">
  3. <i v-if="showIcon" class="icon icon-calendar-act"></i
  4. ><span>{{ text }}</span>
  5. </p>
  6. </template>
  7. <script>
  8. import { formatDate } from "@/utils/utils";
  9. export default {
  10. name: "text-clock",
  11. props: {
  12. showIcon: {
  13. type: Boolean,
  14. default: true,
  15. },
  16. showWeek: {
  17. type: Boolean,
  18. default: true,
  19. },
  20. showApm: {
  21. type: Boolean,
  22. default: true,
  23. },
  24. },
  25. data() {
  26. return {
  27. text: "",
  28. setT: null,
  29. week: ["日", "一", "二", "三", "四", "五", "六"],
  30. };
  31. },
  32. mounted() {
  33. this.parseDate();
  34. this.start();
  35. },
  36. methods: {
  37. parseDate() {
  38. let infos = [];
  39. const now = new Date();
  40. const timeStr = formatDate("YYYY年M月D日_mm:ss", now).split("_");
  41. infos.push(timeStr[0]);
  42. const weekDay = `星期${this.week[now.getDay()]}`;
  43. if (this.showWeek) infos.push(weekDay);
  44. const hourNum = now.getHours();
  45. const val = hourNum > 12 ? hourNum - 12 : hourNum;
  46. const hour = ("00" + val).substr(("" + val).length);
  47. const apm = hourNum < 12 ? "上午" : "下午";
  48. if (this.showApm) infos.push(apm);
  49. infos.push(`${hour}:${timeStr[1]}`);
  50. this.text = infos.join(" ");
  51. },
  52. start() {
  53. this.setT = setInterval(() => {
  54. this.parseDate();
  55. }, 1000);
  56. },
  57. end() {
  58. clearInterval(this.setT);
  59. },
  60. },
  61. beforeDestroy() {
  62. clearInterval(this.setT);
  63. },
  64. };
  65. </script>
  66. <style scoped>
  67. .text-clock {
  68. margin: 0;
  69. }
  70. .text-clock i {
  71. margin-right: 10px;
  72. margin-top: -1px;
  73. }
  74. .text-clock span {
  75. display: inline-block;
  76. vertical-align: middle;
  77. }
  78. </style>