第一步:mian.js 中进行定义
Vue.filter("moneyFilter", function(value, num, type) {
//value是使用过滤器是的表达式或者值,num和tyep中的参数,num和type根据项目需要判断是否传参
return "¥" + value.toFixed(num) + type;
});
参数说明:
moneyFilter表示的是过滤器的名称 函数中的参数解析:
value是通过管道传来的数据 ,必须参数
num在调用过滤器时在圆括号中第一个参数 ,选填参数
type在调用过滤器时在圆括号中第二个参数,选填参数
第二部:组件中使用自定义事件
<div>{{money|moneyFilter(num,type)}}</div>
(项目中一般是另建文件来定义各种过滤器,然后注册在main.js中,main.js一般不写逻辑代码)
列子:创建customFilter.js文件
一、 在customFilter.js文件中写入过滤器
//日期格式过滤器
let dateServer = value => {
return value.replace(/(\d{4})(\d{2})(\d{2})/g, "$1-$2-$3");
};
//金额格式过滤器
let moneyFilter = (value, num, type) => {
return "¥" + value.toFixed(num) + type;
};
//时间格式过滤器
let dateFilter = (input, format = "yyyy-MM-dd hh:mm:ss") => {
var o = {
"M+": input.getMonth() + 1, //月份
"d+": input.getDate(), //日
"h+": input.getHours(), //小时
"m+": input.getMinutes(), //分
"s+": input.getSeconds(), //秒
"q+": Math.floor((input.getMonth() + 3) / 3), //季度
S: input.getMilliseconds() //毫秒
};
if (/(y+)/.test(format))
format = format.replace(
RegExp.$1,
(input.getFullYear() + "").substr(4 - RegExp.$1.length)
);
// 不够2位的前面补0
for (var k in o)
if (new RegExp("(" + k + ")").test(format))
format = format.replace(
RegExp.$1,
RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)
);
return format;
};
export { dateServer, moneyFilter, dateFilter };
二、
main.js 中注册 全局自定义指令
//引入文件
import * as custom from "./common/filters/customFilter";
//注册自定义过滤器,下列代码是引用所有的自定义过滤器
Object.keys(custom).forEach(key => {
Vue.filter(key, custom[key]);
});
三、组件中使用