vue $1-1——动态显示当前日期+时间

vue $1-1——动态显示当前日期+时间

写的不好不要见怪,都是自己一个项目一个项目累积起来的

实现的效果————背景图和透明度需要自己加css哦~

实现效果

<template>
<div>{{currentTime}}</div>
</template>
<script>
export default {
  data() {
    return {
      currentTime: "", //要显示的当前时间
      getTime: new Date(), //获取到的时间
      millisecond: false, //毫秒
    };
    methods: {
    //设置年月日时分秒
    getTime() {
      var str = "";
      var dt = new Date();
      var weekDay = [
        "星期天",
        "星期一",
        "星期二",
        "星期三",
        "星期四",
        "星期五",
        "星期六"
      ];
      this.getTime = this.millisecond? new Date(this.millisecond) : this.getTime; //把毫秒转成日期格式
      str += this.getTime.getFullYear() + "年"; //获取年份
      str += this.setZero(this.getTime.getMonth() + 1, "月", "1"); //获取月份
      str += this.setZero(this.getTime.getDate() + "日", "   "); //获取日
      str += this.setZero(weekDay[dt.getDay()], " "); //获取星期
      str += this.setZero(this.getTime.getHours(), ":"); //获取时
      str += this.setZero(this.getTime.getMinutes(), ":"); //获取分
      str += this.setZero(this.getTime.getSeconds(), ""); //获取秒
      this.currentTime = str;
      this.millisecond= this.millisecond
        ? this.millisecond
        : new Date(this.getTime).getTime(); //把日期格式转成毫秒
      this.millisecond+= 1000; //每次执行增加1秒
    },
    //设置小于10的数字在加0
    setZero(a, b) {
      var str = "";
      str = a < 10 ? "0" + a : a;
      str += b;
      return str;
    }}
 // 创建后执行
  created() {
    this.getTime(); //组件加载先执行一次(因为setInterval定时器要1秒后才执行)
  },
// 挂载后执行
  mounted() {
    this._cache_timeout_id_ = setInterval(this.getTime, 1000); //时间组件挂载完毕执行定时器
  },
// 销毁后执行
  destroyed() {
    window.clearInterval(this._cache_timeout_id_); //时间组件销毁时候停止定时器
  }
  },
</script>
<style scoped>
 
</style>
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值