使用el-table时,某个字段对应多个key值,如何进行展示
前言:
当我们使用下拉框,支持多选的时候,数据库中,存储的是以逗号分隔的key
展示列表的时候,出现存储到数据库中的字段值,如下图所示

显然是不合理的,因此我们需要对其进行转移成,汉字
我们拆分步骤,首先将key值转化为name
computed: {orgTypeMap() {const map = {}this.orgTypeOptions.forEach(option => {map[option.key] = option.name})return map}
}其次,调用方法,解析字符串数据
formatOrgTypes(orgTypeStr) {if (!orgTypeStr) return ''const types = orgTypeStr.split(',')const displayNames = types.map(type => this.orgTypeMap[type] || type)return displayNames.join(',')}
// 代码中的用法
const types = ['wind', 'otherEnergy'];
const displayNames = types.map(type => typeMap[type]);
const result = displayNames.join(','); // "风,其他能源"完整代码如下所示:
<template><el-table :data="tableData"><el-table-column prop="orgType" label="机构类型"><template #default="scope">{{ formatOrgTypes(scope.row.orgType, '/') }}</template></el-table-column></el-table>
</template><script>
export default {data() {return {orgTypeOptions: [{ key: 'wind', name: '风' },{ key: 'otherEnergy', name: '其他能源' },{ key: 'localSubCompany', name: '本地子公司' }],tableData: [{ orgType: 'wind,otherEnergy,localSubCompany' },{ orgType: 'wind,otherEnergy' },{ orgType: 'localSubCompany' }]}},computed: {orgTypeMap() {const map = {}this.orgTypeOptions.forEach(option => {map[option.key] = option.name})return map}},methods: {formatOrgTypes(orgTypeStr, separator = ',') {if (!orgTypeStr) return ''const types = orgTypeStr.split(',')const displayNames = types.map(type => this.orgTypeMap[type] || type).filter(name => name) // 过滤空值return displayNames.join(separator)}}
}
</script>效果图:

