(三)VUE过滤器

   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>

参考链接:

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值