在main.js中定義全局的時間過濾器
//定義全局的時間過濾器
function GetDate(originval){
//需要處理的時間
const dt=new Date(originval*1000)
//年
const y = dt.getFullYear()
//月
const m = (dt.getMonth() + 1 + '').padStart(2,'0')
//日
const d = (dt.getDate() + '').padStart(2,'0')
//時
const hh = (dt.getHours() + '').padStart(2,'')
//分
const mm = (dt.getMinutes() + '').padStart(2,'')
//秒
const ss = (dt.getSeconds() + '').padStart(2,'')
//返回時間格式 yyyy-mm-dd hh:mm:ss
return `${y}-${m}-${d} ${hh}:${mm}:${ss}`
}
//應用於插值表達式中
Vue.filter('dateFormat',GetDate)
//應用於方法中
Vue.prototype.$getDate = GetDate
組件中使用
<template>
<div>
<el-row>
<el-col :span="4">在插值表達式中使用</el-col>
<el-col :span="4">{{dateTime | dateFormat}}</el-col>
</el-row>
<el-row>
<el-col :span="4">方法中獲取使用</el-col>
<el-col :span="4">{{time}}</el-col>
</el-row>
</div>
</template>
<script>
export default {
data(){
return{
dateTime:1588037605,
time:0
}
},
mounted(){
this.getDate()
},
methods:{
getDate(){
const date = this.$getDate(this.dateTime)
this.time = date
}
}
}
</script>
處理結果如下展示: