欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

vue filter过滤器

程序员文章站 2024-02-09 16:02:40
...

vue项目中,如果需要对某个字段进行处理,一般我们会写一个filter,如下,我们新建一个filters.js的文件,然后声明了两个filter,如下所示:

const viCurrency = (val: any) => {
    if (!val) {
        return null;
    }
    let money = Math.ceil(+val);

    return formatMoney(money, 0, "", ".", ",");
}

const formatMoney = (number: any, places: any, symbol: any, thousand: any, decimal: any) => {
    number = number || 0;
    places = !isNaN(places = Math.abs(places)) ? places : 2;
    symbol = symbol !== undefined ? symbol : "$";
    thousand = thousand || ",";
    decimal = decimal || ".";
    let negative = number < 0 ? "-" : "";
    let i = parseInt(number = Math.abs(+number || 0).toFixed(places), 10) + "";
    let j = i.length;
    j = j > 3 ? j % 3 : 0;
    return symbol + negative + (j ? i.substr(0, j) + thousand : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousand) + (places ? decimal + Math.abs(number - (+i)).toFixed(places).slice(2) : "");
}

const sensitiveInfo = (value: string, type: string) => {
    if (type === "phone") {
        // return value.substr(0, 3) + "****" + value.substr(8);
        return value.substr(0, 3) + "******";
    }

    if (type === "bank") {
        const replaceNum = value.substr(0, value.length - 4).replace(/\w/g, "*");
        return replaceNum + value.substr(value.length - 4);
    }

    if (type === "idNum") {
        const replaceNum = value.substr(6, value.length - 4).replace(/\w/g, "*");
        return value.substr(0, 6) + replaceNum + value.substr(value.length - 4);
    }
}

export default {
    viCurrency,
    sensitiveInfo
}

如果我们想要在全局中引用,那我们需要在main.ts文件中引用:

1.引用上述filters文件夹下的filter.js文件

import filters from './filters/filter'

2.注册使用:

Vue.filter('viCurrency', filters.viCurrency);

Vue.filter('sensitiveInfo', filters.sensitiveInfo);

页面中使用:
 

{{ amount | viCurrency}}

这里viCurrency是一个只有一个参数,并且参数为amount的过滤器

{{ fullPhone | sensitiveInfo('phone') }}

这里sensitiveInfo是一个接收两个参数的过滤器函数,其中,fullphone作为第一个参数,字符串phone作为第二个参数