TimeMenu.vue 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. <template>
  2. <div class="showTime">{{ dateFormat(date) }}</div>
  3. </template>
  4. <script>
  5. export default {
  6. name: "TimeMenu",
  7. data() {
  8. return {
  9. date: new Date(), //实时时间
  10. };
  11. },
  12. methods: {
  13. setZero(a) {
  14. //设置小于10的数字在加0
  15. return a < 10 ? "0" + a : a;
  16. },
  17. dateFormat: function (time) {
  18. var date = new Date(time);
  19. var year = date.getFullYear();
  20. /* 在日期格式中,月份是从0开始的,因此要加0
  21. * 使用三元表达式在小于10的前面加0,以达到格式统一 如 09:11:05
  22. * */
  23. var month =
  24. date.getMonth() + 1 < 10
  25. ? "0" + (date.getMonth() + 1)
  26. : date.getMonth() + 1;
  27. var day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
  28. var hours =
  29. date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
  30. var minutes =
  31. date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
  32. var seconds =
  33. date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
  34. // 拼接
  35. return (
  36. year +
  37. "-" +
  38. month +
  39. "-" +
  40. day +
  41. " " +
  42. hours +
  43. ":" +
  44. minutes +
  45. ":" +
  46. seconds
  47. );
  48. },
  49. },
  50. mounted() {
  51. var _this = this;
  52. this.timer = setInterval(() => {
  53. _this.date = new Date(); // 修改日期数据
  54. }, 1000);
  55. },
  56. destroyed() {
  57. if (this.timer) {
  58. clearInterval(this.timer); // 在Vue实例销毁前,清除当前日期定时器
  59. }
  60. },
  61. };
  62. </script>
  63. <style lang="scss" scoped>
  64. </style>