项目场景:
接口数据返回了对应某种情况判断的所有内容,而业务展示只需要展示其中的一种情况,这样就需要前端自己判断一下,过滤处理。
解决方案:
注意:vue
中的filters
过滤器this
指向并不是vue
中的this
,而是undefined
,要让this
获取vue
中data
的数据,操作如下
<template>
<div class="filters">
<!--filtersText是要过滤的值,传递给filtersLabel对象 -->
<div>{{filtersText | filtersLabel}}</div>
</div>
</template>
<script>
// 全局注册that
let that;
export default {
data() {
// 将this赋值给that,供下面过滤器使用
that = this;
return {
arrayList: [
{
"key": "1",
"value": "苹果"
},
{
"key": "2",
"value": "香蕉"
},
{
"key": "3",
"value": "橙子"
},
{
"key": "4",
"value": "猕猴桃"
}
],
filtersText: '1',
}
},
filters: {
filtersLabel: function (dataStr) {
let arrayList = that.arrayList;
let value = '没有水果';
for (let i of arrayList) {
if (i.key == dataStr) {
value = i.value;
break;
}
}
return value;
}
}
}
</script>