本文不多介绍weakMap相关内容,了解看这里
table中比较常见的需求是后端只记录value,前端需要反显对应的 label,话不多说,具体实现如下
const weakMap = new WeakMap();
function list2Map(list = [], option = {label: 'label', value: 'value'}) {
const {label, value} = option;
if (!weakMap.get(list)) {
const res = {};
list.forEach(item => {
res[item[value]] = item[label];
});
weakMap.set(list, res);
}
return weakMap.get(list);
}
export function getLabel(val, list = [], option = {label: 'label', value: 'value'}) {
const obj = list2Map(list, option);
return obj[val] || val;
}
<template>
<el-table border height="100%" :data="tableData">
<el-table-column label="状态" align="center" width="120" show-overflow-tooltip>
<template #default="{row}">
{{ getLabel(row.status, statusList) }}
</template>
</el-table-column>
</el-table>
</template>
<script>
export default {
data() {
return {
tableData: [],
statusList: [{
label: '正常',
value: 1
}, {
label: '紧急',
value: 2
}, {
label: '非常紧急',
value: 3
}]
};
}
};
</script>