vue中如何获取当时时间时分秒

在 Vue 中可以使用 JavaScript 中的 Date 对象来获取当前时间,然后使用 Vue 中的数据绑定将时间显示在页面上。

html 复制代码
<template>
  <div>
    <p>当前时间:{{ time }}</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      time: ''
    }
  },
  mounted() {
    this.getTime()
  },
  methods: {
    getTime() {
      const date = new Date()
      const hours = date.getHours()
      const minutes = date.getMinutes()
      const seconds = date.getSeconds()
      this.time = `${hours}:${minutes}:${seconds}`
      setInterval(() => {
        const date = new Date()
        const hours = date.getHours()
        const minutes = date.getMinutes()
        const seconds = date.getSeconds()
        this.time = `${hours}:${minutes}:${seconds}`
      }, 1000)
    }
  }
}
</script>

在上面的示例中,mounted 钩子函数会在组件挂载后立即执行 this.getTime() 方法来获取时间。getTime() 方法使用 setInterval 来定时获取时间,并将时间格式化成时分秒的形式,然后将其赋值给 this.time 变量。在模板中使用数据绑定来显示时间。

相关推荐
love530love6 小时前
Scoop 完整迁移指南:从 C 盘到 D 盘的无缝切换
java·服务器·前端·人工智能·windows·scoop
i220818 Faiz Ul6 小时前
计算机毕业设计|基于springboot + vue鲜花商城系统(源码+数据库+文档)
数据库·vue.js·spring boot·后端·课程设计
王码码20357 小时前
Flutter for OpenHarmony:Flutter 三方库 bluez 玩转 Linux 风格的蓝牙操作(蓝牙底层互操作)
linux·运维·服务器·前端·flutter·云原生·harmonyos
暴力袋鼠哥9 小时前
基于 Spring Boot 3 + Vue 3 的农产品在线销售平台设计与实现
vue.js·spring boot·后端
chilavert3189 小时前
技术演进中的开发沉思-371:final 关键字(中)
java·前端·数据库
2301_816997889 小时前
Vite构建工具
前端
yuki_uix10 小时前
深入理解 reduce:从面试题到设计思维
前端
凌云拓界10 小时前
TypeWell全攻略(二):热力图渲染引擎,让键盘发光
前端·后端·python·计算机外设·交互·pyqt·数据可视化