需求
最近vue项目中使用elementUI的table组件时,后端返回的表格数据不适合修改,编辑罗辑会直接拿去使用,但是后端返回的数据多为id,或者状态(0,1,2…)。对于用户来说不友好,希望在不改变数据的情况小将id或者状态显示正确的数据。
解决方法
通过在表格标签中使用方法,将对应的id与状态显示为用户需要的内容。
代码
html
<el-table ref="table" :data="tableData" border stripe>
<el-table-column type="selection" width="55" fixed="left"></el-table-column>
<el-table-column v-for="item in tableTitleList" :key="item.key" :prop="item.key" :label="item.title" show-overflow-tooltip min-width="200">
<template slot-scope="scope">
<span v-if="scope.column.property === 'flag'">
{{ setFlag(scope.row.flag) }}
</span>
<span v-else-if="scope.column.property === 'iscall'">
{{ setIsCall(scope.row.iscall) }}
</span>
<span v-else>{{ scope.row[scope.column.property] }}</span>
</template>
</el-table-column>
<el-table-column label="操作" fixed="right" min-width="230">
<template slot-scope="scope">
<el-button class="icon-style" icon="el-icon-view" size="mini" @click="onDetails(scope.row)"></el-button>
<el-button type="warning" class="icon-style" icon="el-icon-edit" size="mini" @click="onEdit(scope.row)"></el-button>
<el-button type="danger" class="icon-style" icon="el-icon-delete" size="mini" @click="onDetails(scope.row)"></el-button>
</template>
</el-table-column>
</el-table>
js
import api from './api'
export default {
data() {
return {
loading: false,
tableData: [],
tableTitleList: []
}
},
created() {
this.init()
},
methods: {
// 初始化
init() {
api.init().then(res => {
if (res.code === 2000) {
this.tableData = res.data
// 其他操作
...
this.$nextTick(() => {
this.loading = false
})
}
}).catch(() => {
this.loading = false
})
})
},
// 数据处理
setFlag(str) {
// 参数为字符串('1,2,3'),需要转为数组后,根据数据字段查询对应的值
const flag = str.split(',')
const flagList = flag.map(ever => {
return this.getDictData('label', ever) // 查询数据字段的方法,返回值为对应的名称
})
return flagList.join(' | ') // 返回结果('张三 | 李四 | 张龙')
},
setIsCall(val) {
// 参数为0 或 1
if (val === 0 || val === '0') {
return '未拨打'
} else {
return '已拨打'
}
},
}
}