vue之过滤器

在vue2.0以前的版本中vue内置的过滤器,但是因为缺乏纯JavaScript的灵活性,现在vue2.0版本中已经删除了内置过滤器,所以需要自己注册过滤器,我们可以定义本地(在某一个template里面定义filter)过滤器,或者定义全局(global)过滤器。需要提醒的是,如果你定义了一个全局过滤器,它必须在Vue实列之前定义,以上两种方式,我们将传递value作为参数。

全局过滤器

下面定义一个全局过滤器,用于在数据前加上大写的VUE。需要注意的是,过滤器定义必须始终位于Vue实例之上,否则会报错。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>vue</title>
    <style>
    </style>
    <script src="./vue.js"></script>
</head>
<body>
    <div id="demo">{{message | toAdd}}</div>
    <script>
        Vue.filter("toAdd",function(value){
            return 'VUE' + value
        })
        var demo = new Vue({
            el: '#demo',
            data: {
            message: '过滤器',
            }
        })
    </script>    
</body>
</html>

本地过滤器

本地过滤器存储在vue组件中,作为filters属性中的函数,我们可以注册多个过滤器存储在其中。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>vue</title>
    <style>
    </style>
    <script src="./vue.js"></script>
</head>
<body>
    <div id="demo">
        <p>{{message | Reverse}}</p>
        <p>{{message | Length}}</p>
    </div>
    <script>
        var demo = new Vue({
            el: '#demo',
            data: {
                message: '过滤器',
            },
             filters: {
                Reverse: function (value) {
                    if (!value) return ''
                    value = value.toString()
                    return value.split('').reverse().join('')
                },
                Length: function(value){
                    return value.length
                } ,
            },
        })
    </script>    
</body>
</html>

过滤器除了单独使用之外,我们还可以对过滤器进行串联使用,也可以在v-bind中使用过滤器。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>vue</title>
    <style>
        .color{
            color:red;
        }
    </style>
    <script src="./vue.js"></script>
</head>
<body>
    <div id="demo">
        <p>{{message | Reverse | Length}}</p>
        <div :class="raw | format">在v-bind表达式中使用过滤器</div>
    </div>
    <script>
        var demo = new Vue({
            el: '#demo',
            data: {
                message: '过滤器',
                raw:'roloc'
            },
             filters: {
                Reverse: function (value) {
                    if (!value) return ''
                    value = value.toString()
                    return value.split('').reverse().join('')
                },
                Length: function(value){
                    return value+value.length
                } ,
                format:function(value){
            return value.split('').reverse().join('')
          } 
            },
        })
    </script>    
</body>
</html>

猜你喜欢

转载自www.cnblogs.com/yuyujuan/p/9783652.html