Vue 顯示時間
1. 實(shí)時獲取系統(tǒng)時間
<template>
<div>
{{ currentDateTime }}
</div>
</template>
export default {
name: 'LockScreen',
data () {
return {
currentDateTime: '',
}
},
mounted () {
this.getCurrentTime()
setInterval(() => {
this.getCurrentTime() // 每秒更新一次時間
}, 1000)
},
methods: {
getCurrentTime () {
const date = new Date()
this.currentTime = this.formatCurrentTime(date)
},
// 格式時間
formatCurrentTime (date) {
// 獲取當(dāng)前時間并打印
const _this = this
const yy = date.getFullYear()
const mm = date.getMonth() + 1
const dd = date.getDate()
const hh = date.getHours()
const mf = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
const ss = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
_this.gettime = yy + '-' + mm + '-' + dd + ' ' + hh + ':' + mf + ':' + ss
return _this.gettime
}
}
}
2. 格式化時間
2.1 封裝全局過濾器
在utils中創(chuàng)建 filter.js 文件文章來源地址http://www.zghlxwxcb.cn/news/detail-821997.html
const filter = {
// value 時間
// args 格式
formatDate: function (value, args) {
const dt = new Date(value)
let year
let month
let date
let hour
let minute
let second
switch (args) {
case 'yyyy-M-d' :
year = dt.getFullYear()
month = dt.getMonth() + 1
date = dt.getDate()
return `${year}-${month}-${date}`
case 'yyyy-M-d H:m:s' :
year = dt.getFullYear()
month = dt.getMonth() + 1
date = dt.getDate()
hour = dt.getHours()
minute = dt.getMinutes()
second = dt.getSeconds()
return `${year}-${month}-${date} ${hour}:${minute}:${second}`
case 'yyyy-MM-dd':
year = dt.getFullYear()
month = (dt.getMonth() + 1).toString().padStart(2, '0')
date = dt.getDate().toString().padStart(2, '0')
return `${year}-${month}-${date}`
case 'yyyy-MM-dd HH:mm:ss' :
year = dt.getFullYear()
month = (dt.getMonth() + 1).toString().padStart(2, '0')
date = dt.getDate().toString().padStart(2, '0')
hour = dt.getHours().toString().padStart(2, '0')
minute = dt.getMinutes().toString().padStart(2, '0')
second = dt.getSeconds().toString().padStart(2, '0')
return `${year}-${month}-${date} ${hour}:${minute}:${second}`
}
}
}
export default filter
2.2 在 main.js 進(jìn)行全局注入
import Vue from 'vue'
import filter from './utils/filter'
for (const key in filter) {
Vue.filter(key, filter[key])
}
2.3 在其他頁面使用
<template>
<div>
{{ new Date() | formatDate('yyyy-MM-dd HH:mm:ss') }}
</div>
</template>
文章來源:http://www.zghlxwxcb.cn/news/detail-821997.html
到了這里,關(guān)于vue關(guān)于時間的操作(持續(xù)更新)(時間格式化、獲取當(dāng)前系統(tǒng)時間)的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!