第一步:引入第三方插件dayjs
npm install dayjs --save
第二步:写好格式化时间的方法
import dayjs from 'dayjs'
export default {
bodyNUllShow(value) {
if (value === 0 || value === '0' || value === '' || value === null) {
return '一'
} else {
return value
}
},
timeToYMDHms(time) {
if (!time && typeof time !== 'string') return ''
return dayjs(time).format('YYYY-MM-DD HH:mm:ss')
},
timeToYMDHm(time) {
if (!time && typeof time !== 'string') return ''
return dayjs(time).format('YYYY-MM-DD HH:mm')
},
timeToYMD(time) {
if (!time && typeof time !== 'string') return ''
return dayjs(time).format('YYYY年MM月DD日')
},
timeToYMD2(time) {
if (!time && typeof time !== 'string') return ''
return dayjs(time).format('YYYY-MM-DD')
},
timeToMDHm(time) {
if (!time && typeof time !== 'string') return ''
return dayjs(time).format('MM-DD HH:mm')
},
timeToFormat(time, format) {
if (!time && typeof time !== 'string') return ''
return dayjs(time).format(format)
},
timeToHMS(time) {
if (!time && typeof time !== 'string') {
time = 0
}
time = Math.floor(time / 1000)
var day = Math.floor(time / (24 * 3600)) // Math.floor()向下取整
var hour = Math.floor((time - day * 24 * 3600) / 3600)
var minute = Math.floor((time - day * 24 * 3600 - hour * 3600) / 60)
var second = time - day * 24 * 3600 - hour * 3600 - minute * 60
return hour + '时' + minute + '分' + second + '秒'
},
wordLimit(word, num) {
let newWord = ''
if (word.length > num) {
newWord = word.substring(0, num) + '...'
} else {
newWord = word
}
return newWord
}
}
第三步,在main.js中引用,这里用到的是vue中的过滤器
import filters from './filters'
// register filters(过滤器)
Object.keys(filters).forEach(key => Vue.filter(key, filters[key]))
第四步,在页面中使用过滤器
<template>
<div class="mt20">{{ time | timeToYMDHms }}</div>
</template>
<script>
export default {
data() {
return {
time: null
}
},
created() {
this.timeStart()
},
methods: {
timeStart() {
// 设置定时器
this.timer = setInterval(() => {
this.time = Date.parse(new Date())
}, 1000)
}
},
}
</script>
<style>
</style>
本文介绍了如何在Vue项目中引入dayjs库,用于时间的格式化,并展示了多个自定义过滤器的实现,如时间转换为年月日、小时分钟等不同格式。此外,还演示了在main.js中注册过滤器并在模板中使用的步骤。
2064

被折叠的 条评论
为什么被折叠?



