vue 动态时间 时分秒

<template>
  <div class="studentRoom">
     <div class="blackboard">当前时间是:{{currentTime}}</div>
  </div>
</template>

<script>
export default {
  name: 'studentRoom',
  data () {
    return {
        timer: "",//定义一个定时器的变量
        currentTime: new Date(), // 获取当前时间
    }
  },
  created() {
    var _this = this; //声明一个变量指向Vue实例this,保证作用域一致
    this.timer = setInterval(function() {
      _this.currentTime = 
         new Date().getHours() +
         ":" +
         new Date().getMinutes() +
         ": " +
         new Date().getSeconds();
    }, 1000);
       
  },
    beforeDestroy() {
    if (this.timer) {
      clearInterval(this.timer); // 在Vue实例销毁前,清除我们的定时器
     }
    },

}
</script>

 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue 中获取当前时分秒,可以使用 JavaScript 的 `Date` 对象。可以通过 `new Date()` 创建一个 `Date` 对象,然后使用该对象的 `getHours()`、`getMinutes()` 和 `getSeconds()` 方法来获取当前时间的小时、分钟和秒数。 假设您要获取当前的时分秒,可以这样写: ```javascript const now = new Date(); // 创建一个 Date 对象,该对象的值为当前时间 const hours = now.getHours(); // 获取当前时间的小时数(0-23) const minutes = now.getMinutes(); // 获取当前时间的分钟数(0-59) const seconds = now.getSeconds(); // 获取当前时间的秒数(0-59) ``` 其中,`hours`、`minutes` 和 `seconds` 变量分别保存了当前时间的小时数、分钟数和秒数。 如果要将当前时分秒格式化为指定的字符串,可以使用字符串模板或第三方库,如 `dayjs`、`moment` 等。 例如,使用字符串模板将当前时分秒格式化为字符串: ```javascript const now = new Date(); const hours = now.getHours(); const minutes = now.getMinutes(); const seconds = now.getSeconds(); const formattedTime = `${hours}:${minutes}:${seconds}`; // 格式化当前时分秒为字符串 ``` 这里使用了字符串模板将 `hours`、`minutes` 和 `seconds` 变量拼接为字符串。如果想要补齐位数,可以使用 `String.prototype.padStart()` 方法。例如,要将分钟数和秒数补齐为两位数,可以这样写: ```javascript const formattedTime = `${hours}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`; ``` 这里使用了 `padStart()` 方法将分钟数和秒数补齐为两位数。该方法接受两个参数:第一个参数是结果字符串的最小长度,第二个参数是用来填充的字符串。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值