Vue中获取当天日期(年-月-日)
warning:
这篇文章距离上次修改已过206天,其中的内容可能已经有所变动。
在Vue中获取当前日期(年-月-日)可以通过创建一个新的Date对象,然后使用相应的方法来获取年、月、日,并且将它们格式化为字符串。以下是一个简单的方法来实现这一功能:
new Vue({
el: '#app',
data: {
currentDate: ''
},
created() {
this.currentDate = this.getCurrentDate();
},
methods: {
getCurrentDate() {
const today = new Date();
const year = today.getFullYear();
const month = (today.getMonth() + 1).toString().padStart(2, '0');
const day = today.getDate().toString().padStart(2, '0');
return `${year}-${month}-${day}`;
}
}
});
在HTML中,你可以这样使用它:
<div id="app">
<p>今天的日期是: {{ currentDate }}</p>
</div>
这段代码在Vue实例被创建时(created
钩子中)会调用getCurrentDate
方法来设置currentDate
数据属性,该方法会返回格式化的当前日期字符串,并在Vue模板中显示出来。
评论已关闭