实现效果:点击按钮,弹框显示第一层数据,点击下拉,调接口展示第二层数据。
vue2 <el-tree> 主要代码:
<el-tree ref="tree" node-key="id" highlight-current :props="capProps" :load="loadNode" lazy show-checkbox @check="check" />
data() { return { capProps: { children: 'children', label: 'label', isLeaf: 'isLeaf' },
loadNode(node, resolve) { if (node.level === 0) { this.API().then(res => { this.capOptions = res.data.body.list this.capOptions.map(item => { item.label = item.deviceTypeAlias item.children = [] // item.disabled = true 第一层全选框不可用 item.isLeaf = false }) return resolve(this.capOptions) }) } if (node.level === 1) { this.API(node.data.id).then(res => { if (res.data.success) { this.childDatas = res.data.body.list this.childDatas.map(item => { item.label = item.deviceAlias item.isLeaf = true }) } node.loading = false return resolve(this.childDatas) }) } },
----------------------------------------------------------------------------------------------------------------------------
vue3 <a-tree> 主要代码: <a-tree v-model:expandedKeys="expandedKeys" v-model:selectedKeys="selectedKeys" node-key="id" :load-data="onLoadData" :tree-data="treeData" checkable @check="check" />
const expandedKeys = ref([]) const selectedKeys = ref([]) const treeData = ref([]) const childData = ref([])
onMounted(() => { getTreeList() })
function getTreeList() { store.dispatch('api', '').then(res => { const treeDatas = res.data.body.list treeDatas.map(item => { item.title = item.deviceTypeAlias item.key = item.id item.isLeaf = false item.children = childData.value }) treeData.value = [...treeDatas] }).catch(() => { }) } const onLoadData = treeNode => { return new Promise(resolve => { if (!treeNode) { resolve() return } store.dispatch('API', treeNode.dataRef.key).then(res => { const data = res.data.body.list childData.value = data.map(item => { item.title = item.deviceAlias item.key = item.id item.isLeaf = true return data }) treeNode.dataRef.children = data treeData.value = [...treeData.value] resolve() }) }) }