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

vue获取当前时间年月日

作者:戮尽逆者   发布日期:2025-07-23   浏览:56

// 在 Vue 组件中获取当前时间的年月日

<template>
  <div>
    <p>当前日期: {{ currentDate }}</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      currentDate: ''
    };
  },
  created() {
    this.updateCurrentDate();
  },
  methods: {
    updateCurrentDate() {
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份从0开始,需要加1,并确保两位数
      const day = String(now.getDate()).padStart(2, '0'); // 确保两位数
      this.currentDate = `${year}-${month}-${day}`;
    }
  }
};
</script>

<style scoped>
/* 样式可以根据需要添加 */
</style>

解释说明:

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

    • 使用 {{ currentDate }} 来显示当前日期。
  2. 脚本部分 (<script>):

    • data 函数返回一个对象,其中包含 currentDate,用于存储格式化后的当前日期。
    • created 生命周期钩子在组件实例创建完成后立即调用 updateCurrentDate 方法。
    • updateCurrentDate 方法通过 new Date() 获取当前时间,并分别提取年、月、日。月份和日期使用 padStart 方法确保为两位数(例如:01, 02, ..., 12)。
    • 最后将格式化后的日期字符串赋值给 currentDate
  3. 样式部分 (<style scoped>):

    • 可以根据需要添加样式,这里暂时为空。

上一篇:vue3 深度监听

下一篇:electron + vue

大家都在看

vue.config.js configu

node.js vue

vue 图表组件

vue3watch监听多个变量

vue查看版本

vue3 reactive对象重新赋值

vue等待几秒

vue3 setup computed

vue screenfull

vue json.stringify

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

Laravel 中文站