vue js获取当前时间
时间: 2023-11-22 22:47:44 浏览: 40
在Vue中,可以使用JavaScript中的new Date()方法获取当前时间。这个方法返回一个表示当前时间的Date对象,包含年、月、日、小时、分钟、秒等信息。以下是一个示例代码:
```javascript
export default {
data() {
return {
currentTime: null,
};
},
mounted() {
this.getCurrentTime();
},
methods: {
getCurrentTime() {
this.currentTime = new Date();
},
},
};
```
在上面的代码中,我们定义了一个名为`currentTime`的数据属性,并在`mounted`钩子函数中调用了`getCurrentTime`方法。`getCurrentTime`方法使用`new Date()`方法获取当前时间,并将其赋值给`currentTime`属性。
如果您想要格式化当前时间,可以使用JavaScript中的一些内置方法,例如`getFullYear()`、`getMonth()`、`getDate()`、`getHours()`、`getMinutes()`和`getSeconds()`等。以下是一个示例代码,演示如何将当前时间格式化为`YYYY-MM-DD HH:mm:ss`的字符串:
```javascript
export default {
data() {
return {
currentTime: null,
};
},
mounted() {
this.getCurrentTime();
},
methods: {
getCurrentTime() {
const now = new Date();
const year = now.getFullYear();
const month = now.getMonth() + 1;
const date = now.getDate();
const hour = now.getHours();
const minute = now.getMinutes();
const second = now.getSeconds();
this.currentTime = `${year}-${month.toString().padStart(2, '0')}-${date.toString().padStart(2, '0')} ${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}:${second.toString().padStart(2, '0')}`;
},
},
};
```
在上面的代码中,我们使用`getFullYear()`、`getMonth()`、`getDate()`、`getHours()`、`getMinutes()`和`getSeconds()`方法获取当前时间的年、月、日、小时、分钟和秒,并使用字符串模板将它们格式化为`YYYY-MM-DD HH:mm:ss`的字符串。