实现图中tree结构和表格互相关联的功能可以参考以下代码
tree结构解析
<template>
<el-tree
ref="treeRef" // 绑定ref后续会调用内部方法 重要!!
:data="storehouseCategoryList" // 数据
show-checkbox
node-key="id"
:props="{children: 'child',label: 'name'}"
:default-expanded-keys="[recordId]" // 默认展开,可以根据自己需求来配置
@check="nodeClickFun"> // 点击复选框触发方法 重要!!
<template #default="{ node, data }"> // 展示配置,可以根据自己需求来配置
<div class="custom-tree-node">
<div>
<span v-if="data.code" style="color: #67c23a; margin-right: 5px">{{ data.code }}</span>
<span style="margin-right: 5px">{{ data.name || 0 }}</span>
<span v-if="data.name !== '框'" style="color: red">({{ data.child.length || 0 }})</span>
</div>
</div>
</template>
</el-tree>
</template>
表格代码解析
<el-table
:data="recordStorehouseData"
id="erp-table"
:row-height="40"
:max-height="575"
stripe
border
lazy
highlight-current-row
table-layout="fixed"
style="width: 100%"
>
<el-table-column label="Date" width="180" /> // 展示字段根据自己需求配置就好 这里就意思一下
<el-table-column label="操作" width="120" align="center">
<template #default="scope">
<el-button size="small" type="danger" @click="deleteBtn(scope.row)">删除</el-button>
</template>
</el-table-column>
</el-table>
JS 部分
<script lang="ts" setup>
import { ref } from 'vue'
import { queryStorehouseSkuList } from '/@/api/storehouse'; // 模拟获取接口
const treeRef = ref() // 绑定tree的ref
const recordStorehouseData = ref([] as any) // 表格绑定的数据
// 点击复选框调用方法,用来操作表格数据
const nodeClickFun = ( data: Tree, dataStatus: Boolean ) => {
/* dataStatus.checkedKeys 可以获取到已经选择数据的数据结构 如:[23,34,54]
示例中就是通过此结构去接口获取表格数据
所以点击复选框触发此事件,获取到对应数据结构调用接口就能动态更新表格里的数据
*/
acquireData(dataStatus.checkedKeys);
}
// 点击删除按钮调用
const deleteBtn = (val: any) => {
/* treeRef.value!.getCheckedKeys(true) 方法可以获取到选中的数据集,
参数切记要使用 true ,使用false 会包含他父元素的值,这样下面的使用会出问题 */
const record = treeRef.value!.getCheckedKeys(true).filter((m) => m !== val.locationId);
/* 过滤掉删除的id,再用 treeRef.value!.setCheckedKeys([]) 方法对复选框选中进行赋值;*/
treeRef.value!.setCheckedKeys(record);
/* 赋完值再进行一次数据跟新调用 */
acquireData(treeRef.value!.getCheckedKeys(false));
};
// 接口调用方法
const acquireData = (list: obect) => {
queryStorehouseSkuList({ ids: list }) // 模拟接口和传值前缀
.then((res: any) => {
recordStorehouseData.value = res.data || [];
})
};
</script>