怎么通过字典,将后端返回的数据value渲染成对应的label?
一个项目会用的很多,所以我直接用全局过滤器,代码可以直接复制用哦
1.首先直接po函数出来,这类数据处理的函数可放在一个专门的文件夹里
//根据字典的value显示label
//第一个参数是传进的label值,第二个参数是所需的字典
export const findByvalue = (value, dic) => {
let result = '';
if (validatenull(dic)) return value;
if (typeof (value) == 'string' || typeof (value) == 'number' || typeof (value) == 'boolean') {
let index = 0;
index = findArray(dic, value);
if (index != -1) {
result = dic[index].label;
} else {
result = value;
}
} else if (value instanceof Array) {
result = [];
let index = 0;
value.forEach(ele => {
index = findArray(dic, ele);
if (index != -1) {
result.push(dic[index].label);
} else {
result.push(value);
}
});
result = result.toString();
}
return result;
};
2.在main.js中注册全局过滤器
import { findByvalue } from '@/util/util'//先引入这个方法
Vue.filter("byValue", findByvalue);//再注册全局过滤器
3.写个字典
export const DIC = {
// 维权状态
rightsStatus: [{
label: '等待维权',
value: 0
}, {
label: '维权中',
value: 1
}, {
label: '维权完成',
value: 2
}, {
label: '维权确认',
value: 3
}, {
label: '不可维权',
value: 4
}]
}
4.把字典引进vue页面再注册,就可以在template上用了!
<template>
<div>
{{status|byValue(DIC.rightsStatus)}}
</div>
</template>
<script>
import { DIC } from "@/const/dic";
export default {
data() {
return {
DIC: DIC,
status:0
}
},
methods:{
//模仿后端数据
getStatus(){
this.status=2;
}
}
}
</script>