VUE允许自定义过滤器,可被用作常见的文本格式化,过滤器可以用在 mustache 插值 和 v-bind 表达式。过滤器应该添加在JavaScript表达式的尾部,由管道符("|")指示。
- 使用语法:
<!-- 在双花括号中 -->
{{ message | capitalize }}
<!-- 在 `v-bind` 中 -->
<div v-bind:id="rawId | formatId"></div>
1、全局过滤器
- 注册或获取全局过滤器:
// 注册
// {string} id 过滤器名称
// {Function} 过滤函数 value为函数接收的处理值,arg为函数传入的参数
Vue.filter('my-filter', function (value, agr1,...) {
// 返回处理后的值
})
// getter,返回已注册的过滤器
var myFilter = Vue.filter('my-filter')
- 使用示例:
<div id="app">
<!-- 对 msg 进行过滤 -->
<p>{{ msg | replace(/world/, "girl") }}</p>
</div>
<script>
// 注册一个全局的替换过滤器
Vue.filter("replace", function(value, regexp, newSubStr){
return value.replace(regexp, newSubStr);
})
var vm = new Vue({
el: "#app",
data: {
msg: "Hello world!"
}
})
</script>
2、私有过滤器
在 Vue 实例的 filters 属性对象中,可以定义私有过滤器,该过滤器只能在该 Vue 实例中使用。注意,私有过滤器在与全局过滤器重名时,会优先使用私有过滤器。
- 注册私有过滤器
var vm = new Vue({
el: "#app",
filters: {
// 在Vue实例中注册私有过滤器
// 属性名称为过滤器名称,属性值为过滤函数
replace: function (value, agr1,...) {
// 返回处理后的值
}
}
})
- 使用示例:
<div id="app">
<!-- 对 msg 进行过滤 -->
<p>{{ msg | replace(/world/, "girl") }}</p>
</div>
<script>
var vm = new Vue({
el: "#app",
data: {
msg: "Hello world!"
},
filters: {
// 在Vue实例中注册私有过滤器
replace: function(value, regexp, newSubStr){
return value.replace(regexp, newSubStr);
}
}
})
</script>
参考链接: