作用:
filter用于对数组进行过滤。它会创建一个新数组,新数组种的元素是通过检查指定数组中符合条件的所有元素。
注意:filter()不会对空数组进行检测、不会改变原始数组
语法:
// 函数 function 为必须,数组中的每个元素都会执行这个函数。且如果返回值为 true,则该元素被保留;
// 函数的第一个参数 currentValue 也为必须,代表当前元素的值
Array.filter(function(currentValue, indedx, arr), thisValue)
目前遇到两种情况需要过滤数据,进而优化代码
情况1:vue中使用过滤器filters
使用场景
用于一些常见的文本格式化。也许后端返回的数据格式并不是最终想要展示出来的,通过过滤器可以进行处理成自己想要展示出来的格式。由“管道”符号指示 ( | )。
局部过滤器的使用方式
-
双花括号插值: {{message | myFilter}}
-
过滤器可以串联,filterA的结果将被传入filterB的参数中:{{message | filterA | filterB}}
-
filterA被定义为接收3个参数的过滤器函数: {{message | filterA(‘arg1’, ‘arg2’)}}
-
vue的生命周期中,如用在methods方法中: this.$options.filters[‘这里是过滤器的名字’]
(‘过滤器的参数’) -
v-bind表达式:
<div :type="message | myFilter"></div>
案例:
//视图
<template>
<view>{{ (item.type == 0 ? item.fromUser : item.toUser) | fromAndToUser(item.fromUser,item.toUser) }}</view>
</template>
//js
<script>
export default {
filters:{//过滤需要的数据
fromAndToUser(value,fromUser,toUser){//value是不可修改的
if ((fromUser.length + toUser.length) > 10) { //是否相加大于10
if (fromUser.length > 5 && toUser.length > 5) {
return value.slice(0,5);
} else {
if (fromUser.length > 5) { //发货人大于5,则收货人小于5
return value.slice(0 , 10 - toUser.length)
} else { //收货人大于5,则发货人小于5
return value.slice(0 , 10 - fromUser.length)
}
}
}else{
return value;
}
}
},
data(){
return{}
}
</script>
全局过滤器的使用方式
// 在创建vue实例之前全局定义过滤器
Vue.filter('capitalize', function (value) {
if (!value) return ''
value = value.toString()
return value.charAt(0).toUpperCase() + value.slice(1)
})
new Vue({
// ...
})
注意:当全局过滤器和局部过滤器重名时,会采用局部过滤器。
情况2:过滤数组
vue中避免在同一元素上同时使用 v-if 与 v-for,v-if 总是优先于 v-for 生效,要判断符合条件的数据,可以用到watch侦听器或者computed计算属性。
使用watch侦听器过滤
export default {
data() {
return {
activeTaskArray:[],//过滤后的新数组
taskArray: [],//接口返回的数据数组
};
},
watch:{//优化: 为了过滤列表中的项目,侦听status状态,让其返回过滤后的列表
status:{
immediate:true,//页面初始化时,立即执行一次
handler(val){//handler固定函数,val值为最新变化之后的值
this.activeTaskArray =this.taskArray.filter((p)=>{
console.log(p)
const statusValue = (this.status == 0 && p.status != 3) || (this.status == 3 && p.status == 3)
return statusValue;
})
}
}
},
}
使用computed计算属性过滤
export default {
data() {
return {
taskArray: [],//接口返回的数据数组
};
},
computed:{//优化: 为了过滤列表中的项目,定义一个计算属性 (activeTaskArray),让其返回过滤后的列表
activeTaskArray(){
console.log("computed")
return this.taskArray.filter((p)=>{//返回过滤后的新数组
console.log(p)
const statusValue = (this.status == 0 && p.status != 3) || (this.status == 3 && p.status == 3)
return statusValue;//返回处理后的值
})
}
},
}