这次给大家带来filter使用案例总结,使用filter的注意事项有哪些,下面就是实战案例,一起来看一下。
1、自定义的过滤器,当然这包括注册在全局和注册在实例化的内部
(1)注册在全局的fliter
(1)全局方法 Vue.filter() 注册一个自定义过滤器,必须放在Vue实例化前面
(2) 过滤器函数始终以表达式的值作为第一个参数。带引号的参数视为字符串,而不带引号的参数按表达式计算
(3)可以设置两个过滤器参数,前提是这两个过滤器处理的不冲突
(4)用户从input输入的数据在回传到model之前也可以先处理
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | nbsp;html>
<meta>
<title>vue自定义过滤器</title>
<script></script>
<meta>
<p>
</p><p>{{message | sum}}</p>
<p>{{message | cal 10 20}}</p> <!--过滤器函数始终以表达式的值作为第一个参数。带引号的参数视为字符串,而不带引号的参数按表达式计算。-->
<p>{{message | sum | currency }}</p> <!--添加两个过滤器,注意不要冲突-->
<input> <!--用户从input输入的数据在回传到model之前也可以先处理-->
<script>
Vue.filter( "sum" , function (value) {
return value + 4;
});
Vue.filter('cal', function (value, begin, xing) {
return value + begin + xing;
});
Vue.filter( "change" , {
read: function (value) {
return value;
},
write: function (newVal,oldVal) {
console.log( "newVal:" +newVal);
console.log( "oldVal:" +oldVal);
return newVal;
}
});
var myVue = new Vue({
el: ".test" ,
data: {
message:12
}
});
</script>
|
filter是默认会传入当前的item,而且filter的第一个参数默认就是当前的item。
(2)注册在实例化内部
上面的例子直接注册在Vue全局上面,其他不用这个过滤器的实例也会被迫接受,其实过滤器可以注册在实例内部,仅在使用它的实例里面注册
上面的程序改写为:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | nbsp;html>
<meta>
<title>vue自定义过滤器</title>
<script></script>
<meta>
<p>
</p><p>{{message | sum}}</p>
<p>{{message | cal 10 20}}</p> <!--过滤器函数始终以表达式的值作为第一个参数。带引号的参数视为字符串,而不带引号的参数按表达式计算。-->
<p>{{message | sum | currency }}</p> <!--添加两个过滤器,注意不要冲突-->
<input> <!--用户从input输入的数据在回传到model之前也可以先处理-->
<script>
Vue.filter( "change" , {
read: function (value) {
return value;
},
write: function (newVal,oldVal) {
console.log( "newVal:" +newVal);
console.log( "oldVal:" +oldVal);
return newVal;
}
});
var myVue = new Vue({
el: ".test" ,
data: {
message:12
},
filters: {
sum: function (value) {
return value + 4;
},
cal: function (value, begin, xing) {
return value + begin + xing;
}
}
});
</script>
|
2、使用js中的迭代函数filter
(1)实例一原文
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | var app5 = new Vue({
el: '#app5' ,
data: {
shoppingList: [
"Milk" , "Donuts" , "Cookies" , "Chocolate" , "Peanut Butter" , "Pepto Bismol" , "Pepto Bismol (Chocolate flavor)" , "Pepto Bismol (Cookie flavor)"
],
key: ""
},
computed: {
filterShoppingList: function () {
var key = this.key;
var shoppingList = this.shoppingList;
return shoppingList.filter( function (item) {
return item.toLowerCase().indexOf(key.toLowerCase()) != -1
});;
}
}
})
|
最终效果实现了根据关键字来过滤列表的功能。
其他的一些Js 迭代方法——filter()、map()、some()、every()、forEach()、lastIndexOf()、indexOf()
相信看了本文案例你已经掌握了方法。
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
暂时没有评论,来抢沙发吧~