ELEMENTUI的表格樹(樹型結構表格),很簡單方式,EL-TABLE只需要小小改動幾個地方
效果:
在el-table中,支持樹類型的數據的顯示。當 row 中包含 children
字段時,被視為樹形數據。渲染樹形數據時,必須要指定 row-key
。支持子節點數據異步加載。
設置 Table 的 lazy
屬性為 true 與加載函數 load
。通過指定 row 中的 hasChildren
字段來指定哪些行是包含子節點。children
與 hasChildren
都可以通過 tree-props
配置。
default-expand-all屬性表示默認展開,不需要展開可以刪除。row-key="id" 和 row里面的屬性有children字段(即數據里面需要有children字段) 是必須的,:tree-props="{children: 'children',hasChildren: 'hasChildren'}可有可無。
如果不是懶加載的話,后端不要設置hasChildren
這個屬性,要不然不能樹形顯示;如果是懶加載,則需要設置hasChildren字段。
下面是vue的表格樹:
<el-table :data="items" row-key="id" :tree-props="{children: 'children', hasChildren: 'hasChildren'}" > <el-table-column label="部門名稱 (編碼)" width="200"> <template slot-scope="scope">{{ scope.row.bmwh1.name }} ({{ scope.row.bmwh1.code }})</template> </el-table-column> <el-table-column label="更新於" width="240"> <template slot-scope="scope">{{ scope.row.bmwh1.updatedAt }}</template> </el-table-column> <el-table-column label="上級部門名稱(編碼)"> <template slot-scope="scope" >{{ scope.row.bmwh1.pid==null?'':`${scope.row.bmwh2.name}(${ scope.row.bmwh2.code})` }}</template> </el-table-column> <el-table-column label="是否啟用"> <template slot-scope="scope"> <el-switch v-model="scope.row.bmwh1.enable" @change="onenable($event,scope.row.bmwh1 )" /> </template> </el-table-column> </el-table>
<script> import { get as httpGet, PAGE_SIZE } from '@/request'; export default { data() { return { items: [], pageSize: PAGE_SIZE, total: 1 }; }, created() { this.onCurrentChange(1); }, methods: { onCurrentChange(page) { httpGet(`/iron/bmwh/?page=${page}&size=${PAGE_SIZE}`) .then(rst => { this.items = rst.items; this.total = rst.total; }) .catch(e => this.$message.error(e.message)); } }
后端視圖層:
public class Bmwhs implements Serializable {</span><span style="color: rgba(0, 0, 255, 1)">private</span> <span style="color: rgba(0, 0, 255, 1)">int</span><span style="color: rgba(0, 0, 0, 1)"> id; </span><span style="color: rgba(0, 0, 255, 1)">private</span><span style="color: rgba(0, 0, 0, 1)"> Bmwh bmwh1; </span><span style="color: rgba(0, 0, 255, 1)">private</span><span style="color: rgba(0, 0, 0, 1)"> Bmwh bmwh2; </span><span style="color: rgba(0, 0, 255, 1)">private</span> List<Bmwhs><span style="color: rgba(0, 0, 0, 1)"> children;
...........
}
接下來需要做的事就是把所有的下級部門視圖層封裝到最上級部門的children視圖層集合屬性里面就可以了。
總結:
一、注意需要在前端表格里面改的是:
:tree-props可以不寫,會有默認值。
二、后端主要改的是:
(1)視圖層里面加入視圖層集合屬性,注意要命名為children(根據:tree-props="{children: 'children', hasChildren: 'hasChildren'}中設置的來定義,如果不想用children,則可以設置children: 'sons'等等,這時候后端數據封裝也得是同名),這樣前端才能渲染成樹型結構。如果不是懶加載,后端不要封裝hasChildren字段,要不然不能渲染成樹形結構。
(2)controller層里面需要做的是:把所有下級部門的視圖層----封裝到----最上級部門視圖層的children集合。
--------====下面不重要====-------------
下面只是例子,不重要!!!根據自己的要求來寫自己 二(2)的東西。
children放空集合也行,不用像下面放null