element-admin表格使用v-for
在基于element-admin开发时,经常会用到表格:
<el-table
:data="list"
border
style="width: 100%;"
>
<el-table-column label="姓名" prop="name" width="80"></el-table-column>
<el-table-column label="年龄" prop="age" width="80"></el-table-column>
<el-table-column label="籍贯" prop="city" width="80"></el-table-column>
</el-table>
export default {
data(){
list:[
{name:"张三",age:18,city:"北京"},
{name:"张三",age:18,city:"北京"},
{name:"张三",age:18,city:"北京"},
{name:"张三",age:18,city:"北京"},
{name:"张三",age:18,city:"北京"},
{name:"张三",age:18,city:"北京"},
{name:"张三",age:18,city:"北京"},
{name:"张三",age:18,city:"北京"},
],
titleList:{
name:"姓名",
age:"年龄",
city:"籍贯"
}
}
}
如果遇到对象中的属性名比较多时,需要些好多的column标签,造成代码多。所以想到可以使用v-for将重复的代码管理起来。
<el-table
:data="list"
border
style="width: 100%;"
>
<el-table-column v-for="(item, index) in Object.entries(titleList)" :key="index" :label="item[1]" :prop="item[0]" width="80"></el-table-column>
</el-table>
Object.entries(titleList)
将titleList中的键值对拆为数组,数组中第一个表示键名,第二个表示键值
在表格中有错误信息表格标红,鼠标移入有提示错误信息
<el-table
:data="list"
border
style="width: 100%;"
class="table"
:cell-class-name="cellTab"
>
<el-table-column v-for="(val, index) in Object.entries(titleList)" :label="val[1]" :prop="val[0]" width="80">
<template slot-scope="scope">
<div v-for="(item, index) in scope.row.excelMistakeList" v-show="scope.row.excelMistakeList.length!=0" :key="index">
<el-tooltip trigger="hover" placement="top" effect="dark" v-model="scope.row.showTool" v-if="item.columnIndex == index" :content="item.describe">
<div class="indicatorValueHtml"></div>
</el-tooltip>
</div>
<div>{{ scope.row[val[0]] }}</div>
</template>
</el-table-column>
</el-table>
data中的数据
export default {
data(){
list:[
{name:"张三",age:18,city:"北京",excelMistakeList:[{columnIndex:'1',rowIndex:1,describe:'指示标识为空或者超长,请检查'}]},
{name:"张三",age:18,city:"北京"},
{name:"张三",age:18,city:"北京"},
{name:"张三",age:18,city:"北京"},
{name:"张三",age:18,city:"北京"},
{name:"张三",age:18,city:"北京"},
{name:"张三",age:18,city:"北京"},
{name:"张三",age:18,city:"北京"},
]
},
methods:{
celltab({row,column,rowIndex,columnIndex}){
if(row.excelMistakeList.length !== 0){
for(val i=0;i<row.excelMistakeList.length;i++){
if(row.excelMistakeList[i].columnIndex === columnIndex &&rowIndex + 1 === row.excelMistakeList[i].rowIndex){
return 'tb1'
}
}
}else{
return ''
}
}
}
}
css中
.table{
.cell{
position:relative;
.indicatorValueHtml{
width:100%;
height:100%;
position:absolute;
top:0;
left:0;
}
}
.tb1{
background:#e56c6c;
color:#fff;
}
}
因为在我的项目中,当表格中为空也是属于异常数据,需要标红提示,但是tooltip为空时,鼠标移入没有反应,所以需要给tooltip加个高度,定位到表格中,这样就解决了表格中没有文字,鼠标移入还可以有错误提示的问题啦。