vue获取当前实际时间,格式为2022-01-01 10:10:10
时间: 2023-02-09 21:12:07 浏览: 95
在 Vue 中获取当前实际时间的格式为 2022-01-01 10:10:10 的方法如下:
1. 在 Vue 的 data 中定义一个变量 currentTime, 用于存储当前时间
```
data() {
return {
currentTime: ''
}
}
```
2. 在 created 钩子函数中获取当前时间, 并将其赋值给 currentTime
```
created() {
this.currentTime = new Date().toLocaleString()
}
```
3. 在模板中使用 {{ currentTime }} 显示当前时间
```
<template>
<div>
{{ currentTime }}
</div>
</template>
```
4. 使用filter转换成目标格式
```
<template>
<div>
{{ currentTime | formatTime }}
</div>
</template>
filters: {
formatTime(val) {
let date = new Date(val)
let y = date.getFullYear()
let m = (date.getMonth() + 1 + "").padStart(2, "0")
let d = (date.getDate() + "").padStart(2, "0")
let h = (date.getHours() + "").padStart(2, "0")
let min = (date.getMinutes() + "").padStart(2, "0")
let s = (date.getSeconds() + "").padStart(2, "0")
return `${y}-${m}-${d} ${h}:${min}:${s}`
}
}
```
5. 如果需要定时刷新,可以使用setInterval函数
```
created() {
setInterval(() => {
this.currentTime = new Date().toLocaleString()
}, 1000)
}
```
6. 也可以使用vue-moment库
```
// 先安装
npm install vue-moment
//main.js
import Vue from 'vue'
import moment from 'moment'
Vue.use(moment)
//template
<template>
<div>
{{ $moment().format('YYYY-MM-DD HH:mm:ss') }}
</div>
</template>
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)