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(名字,函数)

使用时候在你的组件中直接用就可以了

扫描二维码关注公众号,回复: 10055998 查看本文章
 <div>{{numTotal | moneyP}}元</div>

扫码加群,每日更新一篇前端技术文章一起成长。

猜你喜欢

转载自www.cnblogs.com/bbqq1314/p/12545567.html
今日推荐