全局时间的过滤器
// 第一个过滤器
// 将时间戳转为年月日
Vue.filter('dateformat',function(val){
//需要过滤的日期
const date = new Date(val);
// js中单独调用new Date(); 显示这种格式 Mar 31 10:10:43 UTC+0800 2012
但是用new Date() 参与计算会自动转换为从1970.1.1开始的毫秒数
const year = date.getFullYear();
// 实际月份加1
const month = date.getMonth()+1;
const day = date.getDate();
const h = date.getHours();
const m = date.getMinutes();
const s = date.getSeconds();
// 返回年月日 时分秒
return `${year}-${month}-${day} ${h}:${m}:${s}`
})
// 第二个过滤器
Vue.filter('str',function(val) {
console.log(val);
return '今天是' + val;
})
//使用过滤器
<div id="app">
<!-- 过滤器(管道函数) 一般可被用于一些常见的文本格式化 -->
日期是: {{timer | dateformat }}
<hr />
日期是: {{timer | dateformat | str }}
</div>
//需要过滤的日期
data: {
timer: 1599268097326,
// 获取当前时间戳方法1.new Date().getTime() 2.(new Date()).valueOf();3.推荐 +new Date()
},
本文介绍了一个Vue.js应用中的两个过滤器,主要用于日期格式化。第一个过滤器`dateformat`将时间戳转换为年月日时分秒的格式,第二个过滤器`str`则在此基础上添加了'今天是'的前缀。示例中展示了如何在模板中使用这两个过滤器来展示日期。

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



