Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

vue获取当前时间

作者:冰残°零度伤   发布日期:2025-03-11   浏览:129

// 在 Vue 组件中获取当前时间的示例代码

<template>
  <div>
    <p>当前时间: {{ currentTime }}</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      currentTime: ''
    };
  },
  created() {
    this.updateTime();
    // 每秒更新一次时间
    setInterval(this.updateTime, 1000);
  },
  methods: {
    updateTime() {
      const now = new Date();
      // 格式化时间为 "YYYY-MM-DD HH:mm:ss"
      this.currentTime = now.toLocaleString();
    }
  }
};
</script>

<style scoped>
/* 样式可以根据需要自定义 */
</style>

解释说明:

  1. 模板部分 (<template>):

    • 使用 {{ currentTime }} 来显示当前时间。
  2. 脚本部分 (<script>):

    • data() 返回一个对象,其中包含 currentTime,用于存储当前时间。
    • created() 生命周期钩子在组件创建时调用 updateTime 方法,并设置每秒调用一次 updateTime 的定时器。
    • updateTime 方法使用 new Date() 获取当前时间,并通过 toLocaleString() 方法格式化为本地时间字符串,然后将其赋值给 currentTime
  3. 样式部分 (<style scoped>):

    • 可以根据需要自定义样式。

上一篇:vue markdown

下一篇:vue安装教程

大家都在看

vue.config.js configu

node.js vue

vue查看版本

vue等待几秒

vue3 setup computed

vue screenfull

vue json.stringify

vue 遍历list

typescript vue

vue 复选框

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站