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

相关推荐
Csvn2 小时前
Monorepo 迁移血泪史:从 Multi-Repo 到 Turborepo,这 3 个坑我帮你踩完了
前端
星栈2 小时前
Dioxus 多页面怎么做:`dioxus-router`、嵌套路由、`Outlet` 和页面组织,一篇给你讲顺
前端·rust·前端框架
用户987409238872 小时前
用 Remotion + edge-tts 打造中文教学视频全自动流水线
前端
风骏时光牛马2 小时前
Less前端工程化实战:变量混合器与项目样式分层落地
前端
假如让我当三天老蒯2 小时前
Options API(选项式 API) 和 Composition API(组合式 API)
前端·vue.js·面试
SameX2 小时前
iOS 独立开发实践:用 MapKit + 像素渲染实现 Citywalk 轨迹地图 App「雁过留痕」
前端
_柳青杨2 小时前
一文吃透 Node.js 事件循环:从原理到 Node 20+ 重大变更
javascript·后端
skyey2 小时前
页面加载时,深色模式闪白的问题解决
前端
IT_陈寒3 小时前
Java 并行流把我坑惨了,这6小时加班值了
前端·人工智能·后端
anOnion12 小时前
构建无障碍组件之Menu Button pattern
前端·html·交互设计