一、过滤器的一般格式
Vue.js允许自定义过滤器,可被用作一些常见的文本格式化。过滤器可以用在两个地方:mustache插值和v-bind 表达式。过滤器应该被添加在JavaScript表达式的尾部,由“管道”符指示;
过滤器调用时候的格式:
{{ name | nameope }}
过滤器定义格式:
function中的第一个参数已经被规定死了, 永远都是过滤器管道符前面传递过来的数据。
Vue.filter('过滤器名称', function(){})
二、过滤器的使用
1.
<div id="app">
{{ message | msgFormat}}
</div>
var vm = new Vue({
el: "#app",
data: {
message: "hello,Vue!hello,world!hello,JavaScript!"
}
});
//定义一个全局过滤器,名字叫msgFormat
Vue.filter('msgFormat', function (message) {
return message.replace('hello','bye');
});
可以发现的是,此时过滤器只将第一个hello替换成了bye。在replace方法中第一个参数除了可以写字符串以外,也可以写正则表达式。
Vue.filter('msgFormat', function (message) {
return message.replace(/hello/g,'bye');
});
2.
在过滤器的使用中,从页面也可以传递参数到过滤器中:
<div id="app">
{{ message | msgFormat{'hate'} }}
</div>
此时过滤器的写法就变成了如下的样式:
Vue.filter('msgFormat', function (message, arg) {
return message.replace(/hello/g, arg);
});
当然,过滤器也可以传递多个参数,只需要在function的参数位置进行添加,并在replace进行相应的修改即可。
同样,过滤器也可以多次调用:
//定义一个过滤器
Vue.filter('test', function (message) {
return msg+' every Day';
});
<div id="app">
{{ message | msgFormat | test }}
</div>
先把原始的值交给第一个过滤器过滤,再接着给后面的过滤器依次过滤。