使用Ant Design Vue框架的Table組件時,我們通過配置Table組件的colums屬性來生成表頭
<a-table :columns="columns" :data-source="data"></a-table> const columns = [ { dataIndex: 'name', key: 'name', slots: { title: 'customTitle' }, scopedSlots: { customRender: 'name' }, }, { title: 'Age', dataIndex: 'age', key: 'age', }, { title: 'Address', dataIndex: 'address', key: 'address', }, { title: 'Tags', key: 'tags', dataIndex: 'tags', scopedSlots: { customRender: 'tags' }, }, { title: 'Action', key: 'action', scopedSlots: { customRender: 'action' }, }, ];
但是,當我們做智能表單項目的需求是,我們要根據數據庫儲存的JSON對象動態的生成表頭。
當時腦子里的第一個想法是,在拿到后台傳過來的JSON數據之后在JS中根據JSON對象創建一個新的colums,然后生成動態的表頭。這樣做肯定是沒有問題的,代碼省略。
但是后來采取了循環創建 a-table-column 的方式來實現動態表頭。個人感覺這樣更符合邏輯一些
<a-table>
<!-- 定制表格表頭 --> <template v-for="(item, itemIndex) in widgetData.originalLine.fieldList"> <a-table-column v-if="hasGrid(item.id)" :title="item.name" :key="item.id" :width="widthCal(item.id)" :align="alignment(item.id)" > <template slot-scope="text, record"> <div v-if="!item.tableFixedColumnsDisplay"> {{ getTableContent(record,item.id) }} </div> </template> </a-table-column> </template>
<a-table>
這樣就搞定了!