场景:由于使用elementui的el-table自行封装组件时,为了更好地减轻代码负担,我通过动态传值的方法给公共组件传过来了两组数据tableData与columnList。tableData主要是传后端返回来的数据,columnList传表头的种类。其中表头有一项是性别,后端返给我的数据为1与2,1为男,2为女,为了跟方便的转换,我使用了插槽。
<el-table-column
v-for="(item, index) in columnList"
:prop="item.prop"
:label="item.lable"
:key="index"
>
<template slot-scope="{ row }">
<template v-if="item.prop == 'sex'">
<span v-if="row.sex == 1">男</span>
<span v-if="row.sex == 2">女</span>
</template>
</template>
</el-table-column>
是使用途中我发现这么做完只有性别那里转换过了数据,其他列都是空的。
后来我才发现插槽在判断需要转化的列的时候还需要处理不需要转化的列
<el-table-column
v-for="(item, index) in columnList"
:prop="item.prop"
:label="item.lable"
:key="index"
>
<template slot-scope="{ row }">
<template v-if="item.prop == 'sex'">
<span v-if="row.sex == 1">男</span>
<span v-if="row.sex == 2">女</span>
</template>
<template v-else>
<span>{{ row[item.prop] }}</span>
</template>
</template>
</el-table-column>
经过这样处理,其他列的内容也都展示出来了