Home > Web Front-end > JS Tutorial > Vue.js custom filter

Vue.js custom filter

高洛峰
Release: 2016-11-23 17:21:28
Original
1412 people have browsed it

A filter is essentially a function. Its function is that after the user inputs data, it can process it and return a data result.


Vue.js is somewhat similar to the filter syntax in AngularJS. Use the pipe character (|) to connect. The code example is as follows:

{{'abc' | uppercase}}    'abc' => 'ABC'
Copy after login

The built-in filter uppercase of Vue.js is used here to convert the string All letters in are converted to uppercase.


Vue.js supports adding filters wherever expressions appear. In addition to the double brace expression in the above example, it can also be called after the expression of the binding instruction. The code example is as follows:

<div id="app">
    <span v-text="message | uppercase"></span>
</div>
 
<script src="//cdn.bootcss.com/vue/1.0.26/vue.js"></script>
<script>
    new Vue({
        el:&#39;#app&#39;,
        data:{
            message:&#39;hello world!&#39;
        }
    })
</script>
Copy after login

renders as: => HELLO WORLD!


In Vue 2.x, filters can only be used in mustache bindings. To achieve the same behavior in directive bindings, you should use computed properties.


Filters can be connected in series:

{{ message | filterA | filterB }}
Copy after login


Here you can see an example:

<div id="app">
    <h1>{{&#39;ABCDE&#39; |lowercase | capitalize }}</h1>
</div>
 
<script src="//cdn.bootcss.com/vue/1.0.26/vue.js"></script>
<script>
    new Vue({
        el:&#39;#app&#39;,
        data:{
            message:&#39;&#39;
        }
    })
</script>
Copy after login


lowercase filter : Convert data to lowercase

capitalize filter Filter: Change the first letter to uppercase

// 'ABCDE' -> 'abcde' -> 'Abcde'


The filter can accept parameters, which follow the filter name. separated by spaces. The code example is as follows:

{{ message | filterA(&#39;arg1&#39;, arg2) }}
Copy after login


The filter function will always take the value of the expression as the first parameter. Parameters with quotes will be treated as strings, and parameters without quotes will be treated as strings. Treated as data attribute name.


The message here will be used as the first parameter, the string arg1 will be used as the second parameter, and the value of the expression arg2 will be passed to the filter as the third parameter after calculation. At the same time, Vue.js filters support chain calls, and the output of the previous filter can be used as the input of the next filter


Built-in filters

1. Letter operations

Vue.js has built-in capitalize Three filters, uppercase and lowercase, are used to process English characters. Note: These three filters are only used for English strings


1-1, capitalize

capitalize filter is used to convert the first letter in the expression to uppercase

{{&#39;abc&#39; | capitalize}}  // &#39;abc&#39; => &#39;Abc&#39;
Copy after login


1-2. uppercase

uppercase filter is used to convert all letters in the expression to uppercase

{{&#39;abc&#39; | uppercase}}  // &#39;abc&#39; => &#39;ABC&#39;
Copy after login


1-3. lowercase

lowercase filter is used to convert all letters in the expression to uppercase Convert to lowercase

{{&#39;ABC&#39; | lowercase}}  // &#39;ABC&#39; => &#39;abc&#39;
Copy after login


2. Limitations

Vue.js has three built-in filters: limitBy, filterBy, and orderBy, which are used to process and return filtered arrays, such as when used with v-for .

Note: The value of the expression processed by these three filters must be an array, otherwise the program will report an error


2-1, limitBy

The limitBy filter is used to limit the array to the N items before the start elements, where N is specified by the first parameter passed in, indicating the limit, and the default is 0, that is, all elements are taken. The second parameter is optional and is used to specify where to start. For example, if the first parameter is 4 and the second parameter is 5, it means taking 4 elements and starting from the element with subscript 5. The code example is as follows:

<div id="app">
    <ul>
        <!--第二个参数不指定,即取全部,从0开始-->
        <li v-for="item in items | limitBy">{{item}}</li>
    </ul>
</div>
 
<script src="//cdn.bootcss.com/vue/1.0.26/vue.js"></script>
<script>
    new Vue({
        el:&#39;#app&#39;,
        data:{
            items:[1,2,3,4,5,6,7,8,9,10]
        }
    })
</script>
Copy after login

<div id="app">
    <ul>
        <!--只显示5个元素,从0开始-->
        <li v-for="item in items | limitBy 5">{{item}}</li>
    </ul>
</div>
Copy after login

<div id="app">
    <ul>
        <!--显示4个,从下标为3的元素开始  注意:下标是从0开始-->
        <li v-for="item in items | limitBy 4 3">{{item}}</li>
    </ul>
</div>
Copy after login

can also be used like this:

<div id="app">
    <ul>
        <!--取6个,从下标为4的元素开始  注意:数组的长度是arr.length -->
        <li v-for="item in items | limitBy  items.length-4 4">{{item}}</li>
    </ul>
</div>
Copy after login

2-2, filterBy

filterBy filter is more flexible to use. The first parameter can be a string or a function. The filter condition is: 'string || function' + in + 'optionKeyName'


If the first parameter is a string, then each array element will be searched and returns an array containing the elements of that string. The code example is as follows:

<div id="app">
    <ul>
        <li v-for="val in arr | filterBy &#39;a&#39;">{{val}}</li>
    </ul>
</div>
 
<script src="//cdn.bootcss.com/vue/1.0.26/vue.js"></script>
<script>
    new Vue({
        el:&#39;#app&#39;,
        data:{
            arr:[&#39;pear&#39;,&#39;orange&#39;,&#39;cherry&#39;,&#39;lemon&#39;]
        }
    })
</script>
Copy after login

If the array element is an object, the filter will search recursively in all its properties. To narrow the search, you can specify a search field. The code example is as follows:

<div id="app">
    <input v-model="uname">
    <ul>
        <li v-for="user in users | filterBy uname in &#39;uname&#39;">{{user.uname}}</li>
    </ul>
</div>
 
<script src="//cdn.bootcss.com/vue/1.0.26/vue.js"></script>
<script>
    new Vue({
        el:&#39;#app&#39;,
        data:{
            uname:&#39;&#39;,
            users:[
                {uname:&#39;Tom&#39;},
                {uname:&#39;Jerry&#39;},
                {uname:&#39;Kobe&#39;},
                {uname:&#39;James&#39;}
            ]
        }
    })
</script>
Copy after login

Vue.js custom filterVue.js custom filter

If the first parameter of filterBy is a function, the filter will filter based on the return result of the function. At this time, the filterBy filter will call the built-in function filter() in the Javascript array to process the array. Each element in the array to be filtered will be input as a parameter and the function passed in filterBy will be executed.

Only the array elements whose function returns true are eligible and will be stored in a new array. The final return result is this new array.


2-3, orderBy

The function of orderBy filter is to return the sorted array. The filter condition is: 'string || array || function' + 'order>=0 is ascending order || order<=0 is descending order'.

第一个参数可以是字符串、数组或者函数,第二个参数order可选,决定结果为升序或降序排列,默认为1,即升序排列


若输入参数为字符串,则可同时传入多个字符串作为排序键名,字符串之间以空格分隔。代码示例如下:

<ul>
    <li v-for="user in users | orderBy &#39;lastName&#39; &#39;firstName&#39; &#39;age&#39;">
        {{user.lastName}} {{user.firstName}} {{user.age}}
    </li>
</ul>
Copy after login

此时,将按照传入的排序键名的先后顺序进行排序。也可以将排序键名按照顺序放入一个数组中,然后传入一个数组参数给 orderBy 过滤器即可。代码示例如下:

<!--sortKey = [&#39;lastName&#39; &#39;firstName&#39; &#39;age&#39;];-->
<ul>
    <li v-for="user in users | orderBy sortKey">
        {{user.lastName}} {{user.firstName}} {{user.age}}
    </li>
</ul>
Copy after login

升序排列:

<div id="app">
    <input type="text" v-model="a">
    <ul>
        <li v-for="val in arr | orderBy 1">
            {{val}}
        </li>
    </ul>
</div>
 
<script src="//cdn.bootcss.com/vue/1.0.26/vue.js"></script>
<script>
    new Vue({
        el:&#39;#app&#39;,
        data:{
            a:&#39;&#39;,
            arr:[&#39;pear&#39;,&#39;cherry&#39;,&#39;lemon&#39;,&#39;orange&#39;]
        }
    })
</script>
Copy after login

Vue.js custom filter

降序排列:

<div id="app">
    <input type="text" v-model="a">
    <ul>
        <li v-for="val in arr | orderBy -1">
            {{val}}
        </li>
    </ul>
</div>
Copy after login

Vue.js custom filter

3、json 过滤器

Vue.js 中的 json 过滤器本质上是 JSON.stringify() 的精简缩略版,可将表达式的值转换为 JSON 字符串,即输出表达式经过 JSON.stringify() 处理后的结果。

json 可接受一个类型为 Number 的参数,用于决定转换后的 JSON 字符串的缩进距离,如果不输入该参数,则默认为2。


不输入参数,默认为2的示例:

<div id="app">
    <p>{{information | json}}</p>
</div>
 
<script src="//cdn.bootcss.com/vue/1.0.26/vue.js"></script>
<script>
    new Vue({
        el:&#39;#app&#39;,
        data:{
            information:{&#39;name&#39;:&#39;Roger&#39;, &#39;age&#39;:26}
        }
    })
</script>
Copy after login

Vue.js custom filter

为了看到效果,我们输入一个参数20:

<div id="app">
    <p>{{information | json 20}}</p> <!-- 以20个空格的缩进打印一个对象 -->
</div>
Copy after login

Vue.js custom filter

4、currency 过滤器

currency 过滤器的作用是将数字值转换为货币形式输出。

第一个参数接受类型为 String 的货币符号,如果不输入,则默认为美元符号$。

第二个参数接受类型为 Number的小数位,如果不输入,则默认为2.

注意:如果第一个参数采取默认形式,而需要第二个参数修改小数位,则第一个参数不可省略


不输入参数,默认形式

<div id="app">
    <h1>{{amount | currency}}</h1>
</div>
 
<script src="//cdn.bootcss.com/vue/1.0.26/vue.js"></script>
<script>
    new Vue({
        el:&#39;#app&#39;,
        data:{
            amount: &#39;12345&#39;
        }
    })
</script>
Copy after login

Vue.js custom filter

使用其它货币符号:

<div id="app">
    <h1>{{amount | currency &#39;¥&#39;}}</h1>
</div>
Copy after login

Vue.js custom filter

将小数调整为3位:

<div id="app">
    <h1>{{amount | currency &#39;¥&#39; 3}}</h1>
</div>
Copy after login

Vue.js custom filter

5、debounce 过滤器

debounce 过滤器的作用是延迟处理一定的时间执行。其接受的表达式的值必须是函数,因此,一般与 v-on 等指令结合使用。


debounce 接受一个可选的参数作为延迟时间,单位为毫秒。如果没有该参数,则默认的延迟时间为300ms,经过 debounce 包装的处理器在调用之后将至少延迟设定的时间再执行。 如果在延迟结束前再次调用,则延迟时长将重置为设定的时间。


通常,在监听用户 input 事件时使用 debounce 过滤器比较有用,可以防止频繁调用方法。debounce 的用法参考如下:

<input @keyup="onKeyup | debounce 500">
Copy after login

自定义过滤器

1、filter语法

在Vue.js 中也存在一个全局函数 Vue.filter 用于构造过滤器:

Vue.filter(filterName, function(input){...})


该函数接受两个参数,第一个参数为自定义的过滤器名称,第二个参数则是具体的过滤器函数,过滤器函数以值为参数,返回转换后的值


2、单个参数

注册一个名为 reverse 的过滤器,作用是将字符串反转输出。代码示例如下:

<div id="app">
    <input v-model="message">
    <span v-text="message | reverse">{{message}}</span>
</div>
 
<script src="//cdn.bootcss.com/vue/1.0.26/vue.js"></script>
<script>
    Vue.filter(&#39;reverse&#39;,function(message){
        return message.split(&#39;&#39;).reverse().join(&#39;&#39;);
    });
    new Vue({
        el:&#39;#app&#39;,
        data:{
            message:&#39;&#39;
        }
    })
</script>
Copy after login

Vue.js custom filter

注册一个名为 double 的过滤器,作用是将数字补全成两位数输出。代码示例如下

<div id="app">
    <input v-model="value">
    <p v-text="value | double">{{value}}</p>
</div>
 
<script src="//cdn.bootcss.com/vue/1.0.26/vue.js"></script>
<script>
    Vue.filter(&#39;double&#39;,function(value){
        return value<10? &#39;0&#39;+value : value
    });
    new Vue({
        el:&#39;#app&#39;,
        data:{
            value:&#39;&#39;
        }
    })
</script>
Copy after login

Vue.js custom filter

注册一个名为 date 的过滤器,作用是将当前时间毫秒数以年月日时分秒的格式输出。代码示例如下:

<div id="app">
    <p v-text="message | date">{{message}}</p>
</div>
 
<script src="//cdn.bootcss.com/vue/1.0.26/vue.js"></script>
<script>
    Vue.filter(&#39;date&#39;,function(message){
        var now = new Date(message);
        return now.getFullYear()+&#39;-&#39;
                +(now.getMonth()+1)+&#39;-&#39;
                +now.getDate()+&#39; &#39;
                +(now.getHours()<12?&#39;0&#39;+now.getHours():now.getHours())+&#39;:&#39;
                +(now.getMinutes()<10?&#39;0&#39;+now.getMinutes():now.getMinutes())+&#39;:&#39;
                +now.getSeconds();
    });
    new Vue({
        el:&#39;#app&#39;,
        data:{
            message:Date.now()
        }
    })
</script>
Copy after login

Vue.js custom filter

3、多个参数

过滤器函数除了以值作为参数外,也可以接受任意数量的参数,参数之间以空格分隔。代码示例如下:

<div id="app">
    <input v-model="message">
    <p v-text="message | wrap &#39;before&#39; &#39;end&#39;">{{message}}</p>
</div>
 
<script src="//cdn.bootcss.com/vue/1.0.26/vue.js"></script>
<script>
    Vue.filter(&#39;wrap&#39;,function(value, begin, end){
        return begin +&#39; &#39;+ value + &#39; &#39;+ end
    });
    new Vue({
        el:&#39;#app&#39;,
        data:{
            message:&#39;&#39;
        }
    })
</script>
Copy after login

Vue.js custom filter

4、双向过滤器

上面的过滤器都是在 Model 数据输出到 View 层之前进行数据转化的,实际上 Vue.js 还支持把来自视图(input元素)的值在写回模型前进行转化,即双向过滤器

   
Vue.filter(&#39;filterName&#39;,{
    //model ---> view
    //read 函数可选
    read:function(val){
        ...
    },
     
    //view ---> model
    //write 函数将在数据被写入Model 之前调用
    //两个参数分别为表达式的新值和旧值
    write:function(newVal, oldVal){
        ...
    }
})
Copy after login


代码示例如下:

<div id="app">
    <p>{{message}}</p>
    <input type="text" v-model="message | twoWayFilter">
</div>
 
<script src="//cdn.bootcss.com/vue/1.0.26/vue.js"></script>
<script>
    Vue.filter(&#39;twoWayFilter&#39;,{
        read:function(val){
            return &#39;read&#39;+&#39; &#39;+val;
        },
        write:function(newVal, oldVal){
            return oldVal+&#39; &#39;+ &#39;write&#39;;
        }
    });
    new Vue({
        el:&#39;#app&#39;,
        data:{
            message:&#39;hello world&#39;
        }
    })
</script>
Copy after login

在初始情况下,message 表达式的值经过 twoWayFilter 中的 read 函数处理,输出到 view 层

Vue.js custom filter

当我们在 input 框中修改 message 的值时,twoWayFilter 中的 write 函数将在数据输出到 Model 层之前处理,这里将返回 message 的旧值 + 'write',然后输出到 Model层,因此 message的值变更为'hello world write' 并显示到页面上

Vue.js custom filter

常见问题解析

1、filterBy/orderBy 过滤后 $index 的索引

在使用 filterBy 或者 orderBy 对表达式进行过滤时,如果同时需要将 $index 作为参数,此时的 $index将会根据表达式数组或对象过滤后的值进行索引

<ul id="app">
    <li v-for="item in items | orderBy &#39;age&#39;">
        {{item.name}} - {{$index}}
    </li>
</ul>
 
<script src="//cdn.bootcss.com/vue/1.0.26/vue.js"></script>
<script>
    new Vue({
        el:&#39;#app&#39;,
        data:{
            items:[
                {name:&#39;Roger&#39;, age:26},
                {name:&#39;Sarahling&#39;, age:27},
                {name:&#39;Daisy&#39;, age:1}
            ]
        }
    })
</script>
Copy after login


2、自定义filter 的书写位置

自定义 filter 可以写在全局 Vue下,例如:

Vue.filter(&#39;reverse&#39;,function(message){
        return message.split(&#39;&#39;).reverse().join(&#39;&#39;);
    });
Copy after login


也可以写在Vue 实例当中,例如:

var vm = new Vue({
    el:&#39;#example&#39;,
    data:{
         
    },
    filters:{
        //自定义 filter 事件的位置
        reverse:function(value){
            return value.split(&#39;&#39;).reverse().join(&#39;&#39;);
        }
    }
})
Copy after login

   


二者本质上并无区别,可任选一种使用。但是,采用Vue.filter 在全局定义时,需要在实例化 Vue 之前定义,否则自定义的 filter 不起作用


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template