// 在 Vue 组件中获取当前日期的示例代码
<template>
<div>
<p>当前日期是: {{ currentDate }}</p>
</div>
</template>
<script>
export default {
data() {
return {
currentDate: ''
};
},
created() {
this.getCurrentDate();
},
methods: {
getCurrentDate() {
const now = new Date();
// 获取年份、月份(注意:月份从0开始,需要加1)、日期
const year = now.getFullYear();
const month = String(now.getMonth() + 1).padStart(2, '0'); // 确保月份为两位数
const day = String(now.getDate()).padStart(2, '0'); // 确保日期为两位数
// 格式化日期为 YYYY-MM-DD
this.currentDate = `${year}-${month}-${day}`;
}
}
};
</script>
<style scoped>
/* 样式可以根据需要自行添加 */
</style>
data(): 定义了一个 currentDate 变量用于存储格式化后的当前日期。created(): 当组件创建时调用 getCurrentDate 方法来初始化 currentDate。getCurrentDate(): 使用 JavaScript 的 Date 对象获取当前的年、月、日,并将其格式化为 YYYY-MM-DD 的形式。String().padStart(2, '0'): 确保月份和日期始终显示为两位数,不足两位时前面补 0。下一篇:运行vue项目命令
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站