一、问题
在页面中使用Vue通过 {{ data }}来取值,如果数据是日期取出来则是时间戳。
二、解决方案
单独定义用于时间格式化的js 函数date.js,代码如下。在页面中引入date.js,通过{{formatDate(data)}}将时间戳转换为指定日期格式。
1 //给内置的Date对象新增方法Format
2 Date.prototype.Format = function (fmt) { 3 var o = { 4 "M+": this.getMonth() + 1, //月份
5 "d+": this.getDate(), //日
6 "h+": this.getHours(), //小时
7 "m+": this.getMinutes(), //分
8 "s+": this.getSeconds(), //秒
9 "q+": Math.floor((this.getMonth() + 3) / 3), //季度
10 "S": this.getMilliseconds() //毫秒
11 }; 12 if (/(y+)/.test(fmt)) 13 fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length)); 14 for (var k in o) 15 if (new RegExp("(" + k + ")").test(fmt)) 16 fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length))); 17 return fmt; 18 }; 19
20 //工具方法
21 function formatDate(timestramp) { 22 return new Date(timestramp).Format('yyyy-MM-dd'); 23 }
使用date.js后效果如图。