vue-cli 自定義過濾器的使用
阿新 • • 發佈:2018-06-20
() current tps 表達式 允許 渲染 數據 我們 clas
vue-cli 自定義過濾器的使用
vue2.0將內置過濾器去除,所以過濾器需要自己編寫。
Vue.js 允許你自定義過濾器,可被用作一些常見的文本格式化。過濾器可以用在兩個地方:mustache 插值和 v-bind 表達式。過濾器應該被添加在 JavaScript 表達式的尾部,由“管道”符指示:
{{ message | capitalize }}
<div v-bind:id="rawId | formatId"></div>
步驟:
第一步:編寫過濾器文件如(filter.js),我們可以src文件夾中新建文件夾,來存放filter.js文件
在filter.js文件夾中,代碼如下:
首先 import Vue from ‘vue‘
,之後就可以自己編寫過濾器了
import Vue from ‘vue‘ /** * 貨幣格式化 * currencyType 貨幣符號 */ Vue.filter(‘formatPrice‘, function(value = ‘0‘, currencyType = ‘‘) { let res; if (value.toString().indexOf(‘.‘) === -1) { res = (value || 0).toString().replace(/(\d)(?=(?:\d{3})+$)/g, ‘$1,‘) + ‘.00‘ } else { let prev = value.toString().split(‘.‘)[0] let next = value.toString().split(‘.‘)[1] < 10 ? value.toString().split(‘.‘)[1] + ‘0‘ : value.toString().split(‘.‘)[1] res = (prev || 0).toString().replace(/(\d)(?=(?:\d{3})+$)/g, ‘$1,‘) + ‘.‘ + next } return currencyType + res })
代碼中formatPrice為過濾器名稱,之後function的括號中為傳入的需要過濾的數據,return返回處理後的值即可。
第二步:在main.js文件中引入filter.js
import fliter from ‘./api/filter‘
第三步:在組件中使用過濾器,直接使用過濾器函數名,就會在頁面上渲染了
<li>{{123456.4 | formatPrice}}</li>
附:data數據處理過濾器
Vue.filter(‘dateFormat‘, function(val) { if (val != null) { var date = new Date(parseInt(val.replace("/Date(", "").replace(")/", ""), 10)); //月份為0-11,所以+1,月份小於10時補個0 var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1; var currentDate = date.getDate() < 10 ? "0" + date.getDate() : date.getDate(); return date.getFullYear() + "-" + month + "-" + currentDate;//返回年-月-日 2015-6-20 } return "" });
參考資料:https://blog.csdn.net/shuihuanhuan/article/details/75417577
vue-cli 自定義過濾器的使用