vue lic 展示当前时间(js写成组件,dayjs插件)

本文介绍如何在Vue项目中创建一个显示当前时间的组件,使用dayjs插件进行时间处理。首先在components文件夹下新建组件,然后在组件中编写JS代码。接着,通过npm安装dayjs,并在main.js中引入并使用。最后,结合定时器在App中测试,以实现时间的实时更新。
摘要由CSDN通过智能技术生成

js写成组件

效果展示
在这里插入图片描述
在vue lic 的components文件夹下,新建组件CurrentTime.vue
直接上组件代码:

<template>
  <div>
      {{ nowDate + ' ' + nowTime + ' ' + nowWeek }}
  </div>
</template>

<script>
export default {
  name: 'CurrentTime',
    data() {
        return {
            nowDate: "",    // 当前日期
            nowTime: "",    // 当前时间
            nowWeek: ""     // 当前星期
        };
    },
    methods: {
        currentTime() {
            setInterval(this.getDate, 500);
        },
        getDate: function() {
            var _this = this;
            let yy = new Date().getFullYear();
            let mm = new Date().getMonth() + 1;
            let dd = new Date().getDate();
            let week = new Date().getDay();
            let hh = new Date().getHours();
            let mf =
                new Date().getMinutes() < 10
                    ? "0" + new Date().getMinutes()
                    : new Date().getMinutes();
            if (week == 1) {
                this.nowWeek = "星期一";
            } else if (week == 2) {
                this.nowWeek = "星期二";
            } else if (week == 3) {
                this.nowWeek = "星期三";
            } else if (week == 4) {
                this.nowWeek = "星期四";
            } else if (week == 5) {
                this.nowWeek = "星期五";
            } else if (week == 6) {
                this.nowWeek = "星期六";
            } else {
                this.nowWeek = "星期日";
            }
            _this.nowTime = hh + ":" + mf;
            _this.nowDate = yy + "/" + mm + "/" + dd;
        }
    },
    mounted() {
        this.currentTime();
    },
    // 销毁定时器
    beforeDestroy: function() {
        if (this.getDate) {
            console.log("销毁定时器")
            clearInterval(this.getDate); // 在Vue实例销毁前,清除时间定时器
        }
    }
};
</script>

添加组件
App.vue中,添加以下代码

<script>
import CurrentTime from './components/currentTime.vue'

export default {
    components: {
    CurrentTime
  },
}
</script>

且在app中添加 <current-time></current-time>

dayjs利用插件

查看效果
在这里插入图片描述

进入jsday官网

  1. npm安装

npm install dayjs --save

  1. 添加到main.js

import dayjs from ‘dayjs’
Vue.use(dayjs)

  1. 结合定时器,在app中测试查看效果
<template>
  <div id="app">
    <span>{{today}}</span>
  </div>
</template>

<script>
export default {
  data () {
    return {
      today: ''
    }
  },
  mounted () {
    setInterval(() => {
      var dayjs = require('dayjs')
      this.today = dayjs().format('YYYY-MM-DD HH:mm:ss')
    }, 100)
  }
}
</script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值