过滤器的作用
filter主要用于数据展示之前的处理
ps:过滤器只能用在v-bind:指令其语法糖:或者插值表达式中
过滤器的语法
<div id="app">
<p>{{this.person.name}}</p>
<p>{{person.birth|tool|agetool}}</p>
<div>
<button @click="change">测试</button>
</div>
</div>
<script>
new Vue({
el:"#app",
data:{
person:{
name:"jzx",
birth:"1996-03-11"
}
},
methods: {
change(){
console.log("调用了change--methods");
this.person.name="gloria";
}
},
filters:{
tool(date){
console.log("调用了tool--filters");
let age=new Date().getFullYear()-new Date(date).getFullYear();
return age;
},
agetool(age){
console.log("调用了agetool--filters");
return age+"岁";
}
}
});
</script>
过滤器可以实现连调,在连调时会将前面过滤器返回的值传给下一个过滤器作为其参数。过滤器之间用|隔开即可,|前面的数据会作为参数传给其后面的过滤器。函数不需要自己调用,底层会自动调用。
过滤器不传参|符号前的数据会作为后面过滤器的参数,过滤器在调用时传参就是|符号前的数据会作为后面过滤器的第一个参数,
<div id="app">
<p>{{this.person.name}}</p>
<p>{{person.birth|tool|agetool(666,777)}}</p>
<div>
<button @click="change">测试</button>
</div>
</div>
<script>
new Vue({
el:"#app",
data:{
person:{
name:"jzx",
birth:"1996-03-11"
}
},
methods: {
change(){
console.log("调用了change--methods");
this.person.name="gloria";
}
},
filters:{
tool(date){
console.log("调用了tool--filters");
let age=new Date().getFullYear()-new Date(date).getFullYear();
return age;
},
agetool(age,arg1,arg2){
console.log("调用了agetool--filters");
console.log(age,arg1,arg2,1111);
return age+"岁";
}
}
});
</script>