本文實例為大家分享了vue自定義過濾器創(chuàng)建和使用方法,供大家參考,具體內(nèi)容如下
過濾器:生活中有很多例子,凈水器 空氣凈化器 。
過濾器的作用:實現(xiàn)數(shù)據(jù)的篩選、過濾、格式化。
vue1.*版本是有內(nèi)置的過濾器,但是在vue2.*所有的版本都已經(jīng)沒有自帶的過濾器了。
1、過濾器創(chuàng)建
過濾器的本質(zhì) 是一個有參數(shù) 有返回值的方法
new Vue({ filters:{ myCurrency:function(myInput){ return 處理后的數(shù)據(jù) } } })
2、過濾器使用
語法:
<any>{{表達式 | 過濾器}}</any>
舉個例子:
<h1>{{price | myCurrency}}</h1>
3、過濾器高級用法
在使用過濾器的時候,還可以指定參數(shù),來告訴過濾器按照參數(shù)進行數(shù)據(jù)的過濾。
①如何給過濾器傳參?
<h1>{{price | myCurrency('¥',true)}}</h1>
②如何在過濾器中接收到?
new Vue({ filters:{ //myInput是通過管道傳來的數(shù)據(jù) //arg1在調(diào)用過濾器時在圓括號中第一個參數(shù) //arg2在調(diào)用過濾器時在圓括號中第二個參數(shù) myCurrency:function(myInput,arg1,arg2){ return 處理后的數(shù)據(jù) } } })
代碼:
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <script src="js/vue.js"></script> <title></title> </head> <body> <div id="container"> <p>{{msg}}</p> <h1>{{price}}</h1> <h1>{{price | myCurrency('¥')}}</h1> </div> <script> // filter new Vue({ el: '#container', data: { msg: 'Hello Vue', price:356 }, //過濾器的本質(zhì) 就是一個有參數(shù)有返回值的方法 filters:{ myCurrency:function(myInput,arg1){ console.log(arg1); //根據(jù)業(yè)務(wù)需要,對傳來的數(shù)據(jù)進行處理 // 并返回處理后的結(jié)果 var result = arg1+myInput; return result; } } }) </script> </body> </html>
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <script src="js/vue.js"></script> <title></title> </head> <body> <div id="container"> <p>{{msg}}</p> <h1>{{name | myTextTransform(false)}}</h1> </div> <script> new Vue({ el: '#container', data: { msg: 'Hello Vue', name:'Michael' }, filters:{ myTextTransform: function (myInput,isUpper) { if(isUpper) { return myInput.toUpperCase(); } else{ return myInput.toLowerCase(); } } } }) </script> </body> </html>
<!doctype html> <html> <head> <meta charset="UTF-8"> <title>過濾器</title> <script src="js/vue.js"></script> </head> <body> <div id="container"> <p>{{msg}}</p> <h1>{{price}}</h1> <h1>{{price|myCurrency}}</h1> </div> <script> new Vue({ el:"#container", data:{ msg:"Hello VueJs", price:356 }, //過濾器的本質(zhì) 就是一個有參數(shù)有返回值的方法 filters:{ myCurrency:function(myInput){ var result = "$"+myInput; return result; } } }) </script> </body> </html>
最后一個例子是寫死的。
Copyright ? 2019- 91gzw.com 版權(quán)所有 湘ICP備2023023988號-2
違法及侵權(quán)請聯(lián)系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com
本站由北京市萬商天勤律師事務(wù)所王興未律師提供法律服務(wù)