1. 程式人生 > >elemenui-----tree樹形結構踩過的坑

elemenui-----tree樹形結構踩過的坑

num level 正常 獲取 parentId this 編輯 refs 顯示

1、首先,必須保證數據結構是符合要求的,參照官方文檔的數據結構:http://element-cn.eleme.io/#/zh-CN/component/tree

2、做了本公司的用戶管理:後臺返回的樹形菜單數據裏既包含頁面又包含操作權限(頁面操作按鈕),數據大致是這樣:

"menus":[{"children":[{"level":2,"menuIcon":"icon-topology","menuUrl":"/es/topology","menuId":"AA","menuName":"數據分析","sortNum":"11","parentId":"A"}],"level":1,"menuId":"A","menuName":"系統監測管理平臺","sortNum":"1","parentId":""},{"children":[{"children":[{"operationId":1,"operationName":"add_user","operationNameZh":"新增用戶"}],"level":2,"menuIcon":"icon-account","menuUrl":"/config/admin","menuId":"CA","menuName":"用戶管理","sortNum":"21","parentId":"C"}],"level":1,"menuId":"C","menuName":"配置管理","sortNum":"2","parentId":""}]}}

操作權限裏面這樣的結構樹形結構不能展示,所以需要自己將循環meaus,在操作權限裏加上meauId和meauName(至於取值,用操作權限裏的相對應得值就好),這樣保證了能在一個樹裏將操作權限正常顯示出來,能正常勾選;

3、那麽問題又來了,在編輯用戶時,要回顯用戶勾選的頁面和操作權限,這時,又得像上面一樣自己在操作權限裏加上meauId和meauName(至於取值,用操作權限裏的相對應得值就好),如果後臺接口不要求分開傳遞頁面和操作權限的值,直接用tree的getCheckedKeys將選中的id傳給後臺即可。如果要求分開呢,就得將數組裏的頁面id和操作權限id區分開來,註意:假如二級菜單下沒有選擇頁面,只選了菜單,記得要將二級頁面的id也帶上傳遞給後臺。

相應片段代碼:

//頁面權限選中或者取消
handleCheckChange () {
this.allcheckedKeys = []
this.halfCheckedNodes = []
this.checkedMenus =[]
this.checkOperationList =[]
this.allcheckedKeys = this.$refs.tree.getCheckedKeys()
this.halfCheckedNodes = this.$refs.tree.getHalfCheckedKeys()
this.halfCheckedNodes.splice(this.halfCheckedNodes.indexOf(‘0‘), 1)
this.allcheckedKeys.map(item => {
if (isNaN(item)) {
this.checkedMenus.push(item)
} else if (parseFloat(item)) {
this.checkOperationList.push(item)
}
})
this.halfCheckedNodes.map(key => {
this.checkedMenus.push(key)
})
this.checkedMenus = Array.from(new Set(this.checkedMenus))
this.checkOperationList = Array.from(new Set(this.checkOperationList))
console.log(this.checkOperationList)
console.log(this.checkedMenus)
}
//獲取樹形菜單
getMenuList () {
let menuList = JSON.parse(sessionStorage.getItem(‘user‘)).menus
menuList.map((pItem, index) => {
if(pItem.menuId === ‘C‘) {
menuList.splice(index, 1)
}
if (pItem.children) {
if (!pItem.menuName) {
this.$set(pItem, ‘menuName‘, pItem.operationNameZh)
this.$set(pItem, ‘menuId‘, pItem.operationId + ‘‘)
}
pItem.children.map(cItem => {
if (cItem.children) {
if (!cItem.menuName) {
this.$set(cItem, ‘menuName‘, cItem.operationNameZh)
this.$set(cItem, ‘menuId‘, cItem.operationId + ‘‘)
}
cItem.children.map(lItem => {
if (!lItem.menuName) {
this.$set(lItem, ‘menuName‘, lItem.operationNameZh)
this.$set(lItem, ‘menuId‘, lItem.operationId + ‘‘)
}
})
}
})
}
})
//根據返回數據勾選頁面權限
setCheckedMenus(checkData) {
let checkedKeys = [];
checkData.map(pItem => {
if (pItem.children) {
pItem.children.map(cItem => {
if (cItem.children) {
cItem.children.map(lItem => {
if (lItem.operationId) {
checkedKeys.push(lItem.operationId+ ‘‘)
} else if (lItem.menuId) {
checkedKeys.push(lItem.menuId)
}
})
} else {
checkedKeys.push(cItem.menuId)
}
})
}
})
this.$refs[‘tree‘].setCheckedKeys(checkedKeys)

elemenui-----tree樹形結構踩過的坑