vue3 获取当前时间
时间: 2023-06-30 17:16:42 浏览: 131
在Vue3中获取当前时间可以使用JavaScript内置的Date对象。可以在Vue3组件的methods选项中定义一个方法来获取当前时间,例如:
```javascript
export default {
name: 'MyComponent',
data() {
return {
currentTime: ''
}
},
methods: {
getCurrentTime() {
const date = new Date();
const hours = date.getHours();
const minutes = date.getMinutes();
const seconds = date.getSeconds();
this.currentTime = `${hours}:${minutes}:${seconds}`;
}
},
mounted() {
this.getCurrentTime();
setInterval(() => {
this.getCurrentTime();
}, 1000);
}
}
```
在这个例子中,我们在组件的data选项中定义了一个名为`currentTime`的变量来保存当前时间。在`getCurrentTime`方法中,我们使用JavaScript的Date对象获取当前时间,并将其格式化为“小时:分钟:秒”的字符串,然后将其赋值给`currentTime`变量。在组件的mounted方法中,我们首先调用`getCurrentTime`方法以获取当前时间并将其显示在页面上,然后使用setInterval函数每秒钟调用一次`getCurrentTime`方法,以保持时间显示的实时性。
希望这可以帮助到你!