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 变量。在模板中使用数据绑定来显示时间。

相关推荐
laboratory agent开发2 小时前
企业AI Agent落地前,先回答四个工程问题
java·前端·人工智能
微三云 - 廖会灵 (私域系统开发)2 小时前
电商系统国际化架构设计:多语言、多币种、多时区、多税制的全链路实现
java·前端·数据库
不简说3 小时前
JS 代码技巧 vol.5 — 10 个错误处理套路,从 try/catch 到 Error Boundary
前端·javascript·程序员
wordpress资料库3 小时前
Next.js更适合移动开发 不适合web开发
开发语言·前端·javascript·next.js
卷无止境3 小时前
Quarkdown:赋予 Markdown 超能力的现代排版系统
前端·markdown
BerryS3N4 小时前
C++23新特性在CLion中的实战体验:从语法糖到生产力提升
前端·c++23
李明卫杭州4 小时前
Vue 3 `markRaw` 详解:什么时候该让一个对象"别被代理"
vue.js
申君健24864182772024 小时前
# WebGPU 的渲染原理与 Shader
前端
用户83134859306984 小时前
Vue+Threejs实现人物奔跑场景
vue.js·webgl·three.js
随风123weber4 小时前
从前端响应式到后端背压:深度拆解生成式 UI(Generative UI)
前端