vue怎么自定义个过滤器 将时间戳转换为小于24小时显示今天 大于24小时显示昨天 大于48小时显示年-月-日
简单的模仿了 白云苍狗的文章 但是不是起很大的作用
过滤后的结果 2013-03-22 02:20
<p id="app">
<input type="text" v-model="a"/>
<hr />
<span>
{{daitem |times}}
</span>
</p>
<script type="text/javascript">
Vue.filter('times',function (item) {
var date = (typeof item === 'number') ? new Date(item) : new Date((item || '').replace(/-/g, '/'))
// console.log(date)
var diff = (((new Date()).getTime() - date.getTime()) / 1000)
var dayDiff = Math.floor(diff / 86400)
var isValidDate = Object.prototype.toString.call(date) === '[object Date]' && !isNaN(date.getTime())
if (!isValidDate) {
console.error('not a valid date')
return item
}
var today = new Date(date)
var year = today.getFullYear()
var month = ('0' + (today.getMonth() + 1)).slice(-2)
var day = ('0' + today.getDate()).slice(-2)
var hour = ('0' + today.getHours()).slice(-2)
var minute = ('0'+today.getMinutes()).slice(-2)
if (isNaN(dayDiff) || dayDiff < 0 || dayDiff >= 31) {
return `${year}-${month}-${day} ${hour}:${minute}`
}
return dayDiff === 0 && (
diff < 86400 && '今天'
) ||
dayDiff < 2 && '昨天' + `${hour}:${minute}`||
dayDiff < 3 && '前天' + `${hour}:${minute}`||
dayDiff >3 && `${year}-${month}-${day}`
});
var vm = new Vue({
el: '#app',
data: {
daitem: '2013-3-22 2:20'
},
});
</script>
应该用自定义指令更好。