使用定时器setInterval,在Moment.js 时间格式化插件基础上完成当前时间持续动态变化

第一种格式 

1、引入插件

npm install moment --save

 2、js配置:当前需要使用的文件中直接引入

import moment from 'moment';

3、代码实现:定义一个变量进行回显

  3.1、dom部分

<span>    {{ timeData }} </span>

3.2、js代码

<script>
import moment from 'moment'

export default {
    data() {
        return {
            timeData: '',
        }
    },
     created() {
        this.startTime() //初始化获取时间
     },
     methods: {
        //使用定时器setInterval,每隔一秒时间就调用函数
        startTime() {
          this.times = setInterval(() => {
          this.timeData = moment().format("YYYY/MM/DD HH:mm:ss"); //当前时间 格式可根据实际情况空更改为YYYY-MM-DD
      }, 1000);
    },

      beforeDestroy() {
        clearInterval(this.times); //离开当前页面需清除定时器
      }

}

第二种格式:

1、需要引入中文

import moment from 'moment'

import 'moment/locale/zh-cn';

 2、定义内容变量

   timeData: '',

      weekData: '',

      hour: '',

      minute: '',

      second: '',

3、 js格式代码

  startTime() {

      this.times = setInterval(() => {

        moment.locale('zh-cn'); // 设置语言环境为中文

        this.timeData = moment().format("YYYY/MM/DD dddd "); //当前时间

        this.hour = moment().format("HH");  //小时

        this.minute = moment().format("mm"); //分钟

        this.second = moment().format("ss"); //秒

      }, 1000);

    },

4、dom部分

  <div>

            <i class="el-icon-alarm-clock" style="padding-right:10px;"></i>

            {{ timeData }}

          </div>

          <span>{{ this.hour }}</span><strong>:</strong>

          <span>{{ this.minute }}</span><strong>:</strong>

          <span>{{ this.second }}</span>

 时间文字样式参考链接:Vue项目 css下载字体并引入使用_vue css引用ttc字体-CSDN博客

  • 8
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值