过滤器
在vue2.x中允许自定义过滤器,可被用于一些常见的文本格式化。过滤器可以用在两个地方:双花括号插值和 v-bind 表达式 (后者从 2.1.0+ 开始支持)。过滤器应该被添加在 JavaScript 表达式的尾部,由“管道”符号指示:
<!-- 在双花括号中 -->
{{ message | capitalize }}
<!-- 在 `v-bind` 中 -->
<div v-bind:id="rawId | formatId"></div>
一般我们定义局部过滤器:
filters: {
capitalize: function (value) {
if (!value) return ''
value = value.toString()
return value.charAt(0).toUpperCase() + value.slice(1)
}
}
过滤器默认传递的参数是前面变量的值,要想访问methods中的方法和data中的数据,可以参考这篇文章,也可以传递多个参数:
{{ message | filterA('arg1', arg2) }}
这里,filterA 被定义为接收三个参数的过滤器函数。其中 message 的值作为第一个参数,普通字符串 ‘arg1’ 作为第二个参数,表达式 arg2 的值作为第三个参数。
不适场景
当使用过滤器在作用域插槽(slot-scope)中时,由于编译作用域的限制,在作用域插槽中使用过滤器时,无法访问methods中和data中的方法和数据。
譬如:
<el-table-column
align="center"
prop="serviceType"
label="服务类型"
min-width="80"
>
<template slot-scope="scope">
<span>{{ scope.row.serviceType|serviceTypeFilter(this) }}</span>
</template>
</el-table-column>
这里serviceTypeFilter
是访问不到this
的。
解决方案
鉴于此,我们可以直接采用methods中的方法来代替过滤器,比如我们在methods中定义一个方法serviceTypeMethod
,其功能代码可以完全复用之前可以访问this
的serviceTypeFilter
。
之前的serviceTypeFilter
:
serviceTypeFilter(value, that) {
const _this = that._self
if (value) {
const array = value.split(',')
const textArray = array.map(item => _this.pickLabel(serviceTypeOptions, item))
return textArray.join(',')
}
return ''
},
现在的methods版本:
serviceTypeMethod(value) {
if (value) {
const array = value.split(',')
const textArray = array.map(item => this.pickLabel(serviceTypeOptions, item))
return textArray.join(',')
}
return ''
},
使用时直接调用即可:
<el-table-column
align="center"
prop="serviceType"
label="服务类型"
min-width="80"
>
<template slot-scope="scope">
<span>{{ serviceTypeMethod(scope.row.serviceType) }}</span>
</template>
</el-table-column>