vue关于时间的操作(持续更新)(时间格式化、获取当前系统时间)

Vue 显示时间

1. 实时获取系统时间

	
        {{ currentDateTime }}
    

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) {
            // 获取当前时间并打印
            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中创建 filter.js 文件

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 进行全局注入

import Vue from 'vue'
import filter from './utils/filter'

for (const key in filter) {
  Vue.filter(key, filter[key])
}

2.3 在其他页面使用

	
        {{ new Date() | formatDate('yyyy-MM-dd HH:mm:ss') }}
    

本文来自网络,不代表协通编程立场,如若转载,请注明出处:https://net2asp.com/1f7a67b53d.html