实现效果:
如上图所示,实现el-tree的基本使用,回显及联调。
1.点击弹框弹出样式,node-key是id,与后端字段名对应
<Dialog v-model="menuVisible" title="菜单分配">
<el-tree
:data="treeData"
show-checkbox
node-key="menuCode"
:default-expanded-keys="expandKeys"
:default-checked-keys="checkedKeys"
:props="defaultProps"
title="菜单分配"
@check="boxCheck"
ref="treeRef"
/>
<template #footer>
<ElButton
v-if="actionType !== 'detail'"
type="primary"
:loading="saveLoading"
@click="saveMenu"
>
{{ t('exampleDemo.save') }}
</ElButton>
<ElButton @click="menuVisible = false">{{ t('dialogDemo.close') }}</ElButton>
</template>
</Dialog>
2.ref声明,label是文字显示,填写与后端返回数据文字对应的字段名
3.点击按钮方法调用接口,展示数据或回显数据
//菜单分配
const menuAssignment = async (row: any) => {
console.log(row, '表格数据')
role1.value = row.roleCode
menuVisible.value = true
const res = await getTree()
.catch(() => {})
.finally(() => {})
const res1 = await getMenuList({ roleCode: row.roleCode })
.catch(() => {})
.finally(() => {})
if (res) {
treeData.value = res.rows
if (res1) {
// 回显选中菜单
let menuIds = res1.rows
//避免获取不到getNode
setTimeout(() => {
menuIds.forEach((item: any) => {
const node = treeRef.value.getNode(item)
if (node.isLeaf) {
treeRef.value.setChecked(item, true)
chooseKeys.value.push(item)
}
})
}, 100)
}
}
}
4.选中数据调用check方法,将选中的子节点和父节点连接起来存放到chooseKeys数组中
const boxCheck = () => {
let checkedKeys = treeRef.value.getCheckedKeys()
let halfCheckedKeys = treeRef.value.getHalfCheckedKeys()
chooseKeys.value = checkedKeys.concat(halfCheckedKeys)
}
5.点保存将数据传到后端(传参根据后端需求更改)
//菜单保存
const saveMenu = async () => {
// const elTableExpose = await getElTableExpose()
ElMessageBox.confirm('确定要保存吗?', '提醒', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
})
.then(async () => {
saveLoading.value = true
const para = {
roleCode: unref(role1),
// ...multipleSelection.value
rightCodes: chooseKeys.value
}
await saveMenuRole(para).finally(() => {
saveLoading.value = false
})
ElMessage({
type: 'success',
message: '保存成功'
})
getList()
menuVisible.value = false
})
.catch(() => {
ElMessage({
type: 'info',
message: '保存失败'
})
menuVisible.value = false
})
}
最后就完成啦