這兩天在項目中遇到了el-table表頭需要動態變化,也就是點擊不同的標簽顯示對應的表格,主要表頭都不一樣,那么表格也就是動態的,表頭也需要循環
一開始以為很簡單
<el-table
:data="tableData"
style="max-width: 100%">
<el-table-column (item,index) in columnData :key="index" :prop="item.prop" :label="item.label" align="center">
</el-table-column>
</el-table>
然而這樣並不行,然后我又開始了我的百度之旅,看到了一篇文章 https://blog.csdn.net/qq_28929589/article/details/79445354 這里面雖然解決了這個問題但是data的數據格式跟我們返回的不是一樣的,我希望的數據格式也就是elementui里面的格式,再處理會很麻煩,話不多說,上代碼:
<template>
<el-table
:data="tableData"
style="max-width: 100%">
<template v-for="(item,index) in headArr" >
<el-table-column :key="index" :prop="item.prop" :label="item.label" align="center">
<template scope="scope">
<span>
{{scope.row[item.prop]}}
</span>
</template>
</el-table-column>
</template>
</el-table>
</template>
<script>
export default {
data(){
return{
headArr:[
{label:'姓名' , prop : 'name'},
{label:'年齡' , prop : 'age'},
{label:'電話' , prop : 'phone'},
],
tableData:[
{name:'zhangsan',age:'16',phone:'111'},
{name:'lisi',age:'18',phone:'221'}
]
}
}
}
</script>
具體為啥要這么寫我還不是很懂,如果有了解的朋友可以留言告訴我,讓我學習一下