Vue引入全局过滤器
创建单独的文件
加上时间过滤函数
将formatDate 暴露 export 出来
// 时间戳转时分秒
function getformatDate (date, fmt) {
if (/(y+)/. test (fmt)) {
fmt = fmt.replace(RegE xp .$1, (date.getFullYear() + '').s ub str(4 - RegExp.$1.length));
}
let o = {
'M+': date.getMonth() + 1,
'd+': date.getDate(),
'h+': date.getHours(),
'm+': date.getMinutes(),
's+': date.getSeconds()
};
for (let k in o) {
if (new RegExp(`(${k})`).test(fmt)) {
let str = o[k] + '';
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftZero(str));
}
}
return fmt;
};
function padLeftZero (str) {
return ('00' + str).substr(str.length);
};
// 时间过滤
export function formatDate(time) {
return getformatDate(new Date(time), " yy yy-MM-dd hh:mm");
}
在m ai n.js中全局引入
import * as filters From './filters' // global filters
// register global util IT y filters.
Object.keys(filters).for each (key => {
Vue.filter(key, filters[key])
})
在组件中使用formatDate过滤时间戳
<el -t able :data="item.children" style="width: 100%">
<el-table-column PR op="title" label="标题"></el-table-column>
<el-table-column prop="portN am e" label="上传单位"></el-table-column>
<el-table-column prop="createdTime" label="上传时间">
<template slot -s co PE ="scope">{{scope.row.createdTime | formatDate}}</template>
</el-table-column>
</el-table>
页面显示
vue全局过滤器配置
有时一个过滤器需要在项目中多次使用,此时可以将该过滤器定义为全局过滤器,全局过滤器在main.js下配置。
以时间过滤器 为例 ,当为局部过滤器写为:
filters: {
timeForm(val) {
if (typeof (value) == "un define d" || value === null) return "";
let date = new Date(value);
VAR y = date.getFullYear();
var m = date.getMonth() + 1;
var d = date.getDate();
if (isNaN(y) && y != 0) {
y = " ";
}
if (isNaN(m) &am p; & m != 0) {
m = " ";
} else {
(m < 10 ? "0" + m : m);
}
if (isNaN(d) && d != 0) {
d = " ";
} else {
(d < 10 ? "0" + d : d);
}
return y + "-" + m + "-" + d + " " + date.toTimeString().substr(0, 5);
}
现在我们把它设置成全局过滤器
Vue.filter('timeForm', function (value) {
if (typeof (value) == "undefined" || value === null) return "";
let date = new Date(value);
var y = date.getFullYear();
var m = date.getMonth() + 1;
var d = date.getDate();
if (isNaN(y) && y != 0) {
y = " ";
}
if (isNaN(m) && m != 0) {
m = " ";
} else {
(m < 10 ? "0" + m : m);
}
if (isNaN(d) && d != 0) {
d = " ";
} else {
(d < 10 ? "0" + d : d);
}
return y + "-" + m + "-" + d + " " + date.toTimeString().substr(0, 5);
});
var timeForm = Vue.filter('timeForm');
直接定义为:Vue.filter(& # 39;timeForm', function (value) { //过滤代码} 然后定义一下过滤器:var timeForm = Vue.filter('timeForm')
使用的时候和局部过滤器相同方式使用,直接{{ value | filter }} 即可
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。
您可能感兴趣的 文章 : Vue的filters(本地)或filter(全局)过滤常用数据类型解析 vue中的局部过滤器和全局过滤器代码实操 vue全局过滤器概念及注意事项和基本使用方法 Vue封装全局过滤器Filters的步骤 Vue的全局过滤器和私有过滤器的实现 vue-cli 3 全局过滤器的实例代码详解 Vue中全局常用的过滤方法解读
总结
以上是 为你收集整理的 Vue如何引入全局过滤器 全部内容,希望文章能够帮你解决 Vue如何引入全局过滤器 所遇到的问题。
如果觉得 网站内容还不错, 推荐好友。
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://haodehen.cn/did203921