全局过滤器
1.mian.js同级目录下新建文件夹filter,文件夹下新建filter.js:
let transformMobile=val=>{ //手机号码隐藏中间4位
let mobile = val + '';
if (mobile && mobile.length === 11) {
const reg = /^(\d{3})\d{4}(\d{4})$/
return mobile.replace(reg, '$1****$2')
} else {
return val
}
};
export { transformMobile}
2.mian.js引入:
import * as custom from './filter/filter';
Object.keys(custom).forEach(key => {
Vue.filter(key, custom[key])
});
3.组件使用:
<div @click.stop>
<a :href="'tel:' + mobile"> {{mobile| transformMobile}} </a>
</div>
data(){
return{
mobile: '13612345678',
}
}
注:以上示例显示结果: 136****5678
组件内部过滤器
<template>
<div><span>{{type | transformType(typeList)}}</span></div>
</template>
<script>
export default {
data(){
return{
type: 1,
typeList:[ //接口获取的类型列表
{typeName:'中国邮政', code:0},
{typeName:'顺丰快递', code:1},
{typeName:'中通快递', code:2}
],
}
},
filters: {
transformType(val,typeList){
if(typeList.length>0){
for(let i=0; i<typeList.length; i++){
if (typeList[i].code == val) {
return typeList[i].typeName;
}
}
}else {
return '未知'
}
}
},
}
</script>
注:以上示例显示结果: 顺丰快递
网友评论