Vue3 element-Plus el-tree 权限树 传值给后端及回显问题

内容:
权限在新增人员时候选择传给后端并且编辑回显

坑:

1.传给后端的权限数组需要传父级id

例如:一级目录下有二级目录和2-2目录,选了2-2目录,需要把一级目录的id也给后端

2.回显的时候后端会把权限数组id都给你(包括一级目录),如果直接回显的话会默认一级下所有目录都选中

 

代码参考

<el-tree ref="treeRef" :data="treeData" :default-checked-keys="roleForm.menuIds" default-expand-all show-checkbox node-key="id" :props="defaultProps" @check="setCheckedNodes" />

js部分

const treeRef = ref<InstanceType<typeof ElTree>>()
const treeData = ref([])
const newIds = ref([] as any[] | undefined | null)

const editItem = (index?: any, row?: any) => {
  dialogVisible.value = true
  title.value = "修改角色"
  user_info({ id: row.id }).then((res: any) => {
    roleForm.id = res.data.id
    roleForm.roleName = res.data.roleName
    roleForm.roleSort = res.data.roleSort
    roleForm.remark = res.data.remark
    newIds.value = res.data.menuIds
    //权限树回显
    treeRef.value?.setCheckedKeys(res.data.menuIds)
    const arr: any = []
    res.data.menuIds.forEach((item: any) => {
      if (!treeRef.value?.getNode(item).childNodes || !treeRef.value?.getNode(item).childNodes.length) {
        arr.push(item)
      }
    })
    roleForm.menuIds = arr
    treeRef.value?.setCheckedKeys(arr)
  })
}


const getTreeData = () => {
  menu_list({}).then((res) => {
    treeData.value = JSON.parse(JSON.stringify(res.data))
    treeData.value.map((org) => mapTree(org))
  })
}

const mapTree = (org: any) => {
  const haveChildren = Array.isArray(org.children) && org.children.length > 0
  org.label = org.menuName
  if (haveChildren) {
    org.children.map((i: any) => mapTree(i))
  }
}

const setCheckedNodes = (arr: any, val: any) => {
  roleForm.menuIds = val.checkedKeys
  newIds.value = treeRef.value?.getCheckedNodes(false, true).map((i) => i.id)
}


let params = {
    roleName: roleForm.roleName,
    roleSort: roleForm.roleSort,
    remark: roleForm.remark,
    menuIds: newIds.value
}
 

 

posted @ 2023-06-20 13:13  阿蒙不萌  阅读(820)  评论(0编辑  收藏  举报