首先,使用過element-ui的table組建的同學都知道,每次使用的時候表頭字段都要一個一個的去寫,寫起來很麻煩,既不美觀又浪費時間,基於以上原因,對table組件進行二次封裝,使我們在使用的時候更加簡單方便。
這里只是簡單的封裝,同學們若是感興趣可以加以完善,若有問題可以一起討論。

//封裝的table組件 <template> <!-- 列表 --> <el-table stripe :border="border" :data="dataSource" @selection-change="handleSelectionChange" v-loading="listLoading" @row-dblclick="rowClick" highlight-current-row @row-click="clickTable" ref="refTable" @expand-change="expandChange" > <!--數據源--> <el-table-column v-for="(column, index) in columns" header-align="center" v-if="column.isShow" :sortable="column.hasSort" :key="column.prop" :prop="column.prop" :label="column.label" :align="column.align" :width="column.width"> </el-table-column > </el-table> </template> <script> export default { name:"tables", props:{ dataSource: {// 表格數據源 默認為空數組 type: Array, default: ()=> [] }, columns: {// 表格的字段展示 默認為空數組 type: Array, default: ()=>[] } }, components: { // }, watch:{ // }, mounted(){ // }, methods: { // } } </script> <style lang="scss"> // </style>
封裝完成后怎么調用這個組件呢?

//調用封裝好的table組件 <template> //這里僅傳入列表數據和表頭數據,如有其它需求可以增加傳遞參數 <tables :dataSource="dataSource" :columns="columns"></tables> </template> <script> import tables from './table.vue' //引入組件 export default { data() { return { dataSource:[{ 'createTime':123, 'times':123, 'username':'jj', 'deptName':'ii', 'status':'0', },{ 'createTime':123, 'times':123, 'username':'jj', 'deptName':'ii', 'status':'0', },{ 'createTime':123, 'times':123, 'username':'jj', 'deptName':'ii', 'status':'0', }], columns:[{ hasSort: false, //<Boolean> 是否排序 isShow: true, //<Boolean> 是否展示 prop: 'createTime', //<String> 對應屬性名 label: '日期', //<String> 表頭標簽 align: 'center',//表頭內容是否居中 width: 200, // 列寬 },{ hasSort: false, //<Boolean> 是否排序 isShow: true, //<Boolean> 是否展示 prop: 'times', //<String> 對應屬性名 label: '時間', //<String> 表頭標簽 align: 'center'//表頭內容是否居中 },{ hasSort: true, //<Boolean> 是否排序 isShow: true, //<Boolean> 是否展示 prop: 'username', //<String> 對應屬性名 label: '名字', //<String> 表頭標簽 align: 'center'//表頭內容是否居中 },{ hasSort: true, //<Boolean> 是否排序 isShow: true, //<Boolean> 是否展示 prop: 'deptName', //<String> 對應屬性名 label: '部門名稱', //<String> 表頭標簽 align: 'center'//表頭內容是否居中 },{ hasSort: true, //<Boolean> 是否排序 isShow: true, //<Boolean> 是否展示 prop: 'status', //<String> 對應屬性名 label: '狀態', //<String> 表頭標簽 align: 'center'//表頭內容是否居中 } ] } }, components: { tables,//注冊table組件 }, watch:{ // }, mounted(){ // }, methods: { // } } </script> <style lang="scss"> // </style>
下面是我的公眾號二維碼,歡迎同學們關注,大家一起學習,一起進步。