如何使用vue组件实现使用mounted钩子函数写一个动态刷新时间效果?

要使用 Vue 组件实现动态刷新时间效果,你可以在组件的 mounted 钩子函数中设置一个定时器,以每隔一定时间更新显示的时间。下面是一个简单的示例代码:

<template>
  <div>
    <p>当前时间:{{ formattedTime }}</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      formattedTime: ''
    };
  },
  mounted() {
    this.updateTime(); // 初始化时先更新时间
    this.timer = setInterval(this.updateTime, 1000); // 每隔一秒更新一次
  },
  beforeDestroy() {
    clearInterval(this.timer); // 组件销毁时清除定时器
  },
  methods: {
    updateTime() {
      const now = new Date();
      const year = now.getFullYear();
      const month = this.padZero(now.getMonth() + 1);
      const day = this.padZero(now.getDate());
      const hours = this.padZero(now.getHours());
      const minutes = this.padZero(now.getMinutes());
      const seconds = this.padZero(now.getSeconds());

      this.formattedTime = `${year}年${month}月${day}日 ${hours}时${minutes}分${seconds}秒`;
    },
    padZero(value) {
      return value.toString().padStart(2, '0');
    }
  }
};
</script>

 

在上面的代码中,我们定义了 formattedTime 作为显示格式化后的时间的数据属性。在 updateTime 方法中,我们获取当前时间的年、月、日、时、分、秒,并使用模板字符串拼接成指定的格式。

为了确保月、日、时、分、秒的值始终显示为两位数(例如:01、02、...、09、10、...、12、...等等),我们还定义了一个辅助函数 padZero,它会在数字小于 10 时,在其前面补零。

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值