TextClock.vue 991 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. <template>
  2. <p class="text-clock">现在是{{ text }}</p>
  3. </template>
  4. <script>
  5. import { formatDate } from "@/utils/utils";
  6. export default {
  7. name: "text-clock",
  8. data() {
  9. return {
  10. text: "",
  11. setT: null,
  12. week: ["日", "一", "二", "三", "四", "五", "六"],
  13. };
  14. },
  15. mounted() {
  16. this.parseDate();
  17. },
  18. methods: {
  19. parseDate() {
  20. const now = new Date();
  21. const timeStr = formatDate("YYYY年M月D日_mm:ss", now).split("_");
  22. const weekDay = `星期${this.week[now.getDay()]}`;
  23. const hourNum = now.getHours();
  24. const val = hourNum > 12 ? hourNum - 12 : hourNum;
  25. const hour = ("00" + val).substr(("" + val).length);
  26. const apm = hourNum < 12 ? "上午" : "下午";
  27. this.text = `${timeStr[0]} ${weekDay} ${apm} ${hour}:${timeStr[1]}`;
  28. this.setT = setTimeout(() => {
  29. this.parseDate();
  30. }, 1000);
  31. },
  32. },
  33. beforeDestroy() {
  34. if (this.setT) clearTimeout(this.setT);
  35. },
  36. };
  37. </script>