定义公共js文件filters.js
import Vue from 'vue'
Vue.filter('timeFilter', function(str, type) {
if (!str) {
return '- -'
}
str = String(str).length <= 10 ? str * 1000 : str;
let formatTime = (a) => parseInt(a) < 10 ? '0' + parseInt(a) : parseInt(a);
let t = new Date(str);
let year = t.getFullYear();
let month = formatTime(t.getMonth() + 1);
let day = formatTime(t.getDate());
let hours = formatTime(t.getHours());
let minutes = formatTime(t.getMinutes());
let seconds = formatTime(t.getSeconds());
if (type == "ymd") {
return `${year}-${month}-${day}`;
} else if (type == 'hms') {
return `${hours}:${minutes}:${seconds}`;
} else if (type == 'ms') {
return `${minutes}:${seconds}`;
} else if (type == 'ymdhm') {
return `${year}-${month}-${day} ${hours}:${minutes}`;
} else if (type == "article") {
return `${month}月${day}号 ${hours}:${minutes}`
} else if (type == "order") {
return `${year}年${month}月${day}号`
} else {
return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}
})
Vue.filter('subStr', function(str, num = 100) {
return str.length > num ? (str.substr(0, num) + "...") : str.substr(0, num)
})
Vue.filter('dateFilter', function(str) {
return str.slice(0, 4) + '-' + str.slice(4, 6) + '-' + str.slice(6);
});
Vue.filter('telHide', function(str) {
return str.replace(/(\d{3})\d{4}(\d*)/, '$1****$2')
});
Vue.filter('nameHide', function(name) {
if (name.length === 2) {
return new Array(name.length).join('*') + name.substr(-1)
} else {
return (name.substr(0, 1) + new Array(name.length - 1).join('*') + name.substr(-1))
}
});
Vue.filter('IDcardHide', function(name) {
return name.replace(/(\d{8})\d{8}(\d*)/, '$1********$2')
});
Vue.filter('digitalConversion', function(str) {
let num = Math.abs(str);
if (String(num).length < 5) {
return num;
} else {
return (num / 10000).toFixed(1) + 'W';
}
})
Vue.filter('timeAgo', function(time) {
time = String(time).length <= 10 ? time * 1000 : time;
var arr = [
[],
[]
],
stamp = new Date().getTime() - new Date(time).getTime();
if (stamp > 1000 * 60 * 60 * 24 * 8) {
stamp = new Date(time);
arr[0][0] = digit(stamp.getFullYear(), 4);
arr[0][1] = digit(stamp.getMonth() + 1);
arr[0][2] = digit(stamp.getDate());
return arr[0].join('-') + ' ' + arr[1].join(':');
}
if (stamp >= 1000 * 60 * 60 * 24) {
return ((stamp / 1000 / 60 / 60 / 24) | 0) + '天前';
} else if (stamp >= 1000 * 60 * 60) {
return ((stamp / 1000 / 60 / 60) | 0) + '小时前';
} else if (stamp >= 1000 * 60 * 2) {
return ((stamp / 1000 / 60) | 0) + '分钟前';
} else {
return '刚刚';
}
})
function digit(num, length) {
var str = '';
num = String(num);
length = length || 2;
for (var i = num.length; i < length; i++) {
str += '0';
}
return num < Math.pow(10, length) ? str + (num | 0) : num;
}
main.js引入过滤器
import '@/common/js/filters';
页面中使用
<div class="time">{{item.createtime |timeFilter}} 至 {{item.endtime |timeFilter}}</div>
<div class="time">{{item.createtime |timeFilter(第二个参数,第三个参数)}} 至 {{item.endtime |timeFilter}}</div>