vue中引入公用過濾器?


比如我們封裝一個金錢的過濾器:

 

不廢話,直接上代碼

 

在main.js平級新建filter文件夾,里面新建index.js和money.js

 

index.js

import {
    moneyP
} from './money' export default moneyP; 

注意這里不要用module.exports導出了,會報錯。

// module.exports = {
//     normalTime
// }

money.js里面

function fmoney(s){ let n = 2; n = n > 0 && n <= 20 ? n : 2; s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(n) + ""; var l = s.split(".")[0].split("").reverse(), r = s.split(".")[1]; let t = ""; for(let i = 0; i < l.length; i ++ ) { t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : ""); } return t.split("").reverse().join("") + "." + r; } export const moneyP = (num) => { if(num == 0) { let outnum = '0.00' return outnum; } else { if(num != '') { if(num < 0) { let outnum = fmoney(-num) return '-' + outnum } else { let outnum = fmoney(num) return outnum } } } } 

在main.js里面引入:

//引入過濾器
import filters from './filter' Vue.filter('moneyP',filters) 

//Vue.filter(名字,函數)

使用時候在你的組件中直接用就可以了

 <div>{{numTotal | moneyP}}元</div>

掃碼加群,每日更新一篇前端技術文章一起成長。

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM