change data layout
The pid of the child node is equal to the id of the parent node
Implemented with the element component library
raw data:
{
id: '1',
name: '张三',
pid: '0'
},
{
id: '2',
name: ' 李四',
pid: '0'
},
{
id: 'a1',
name: '王五',
pid: '1'
},
{
id: 'a2',
name: '王小五',
pid: '1'
}
After conversion:
{
id: '1',
name: '张三',
pid: '0',
children: [
{
id: 'a1',
name: '王五',
pid: '1'
},
{
id: 'a2',
name: '王小五',
pid: '1'
}
]
},
{
id: '2',
name: ' 李四',
pid: '0'
}
exhibit
Encapsulate a method utils/terrData.js
export const getDepartmentsData = (list, parentId) => {
const result = []
list.forEach(item => {
if (item.pid === parentId) {
const children = getDepartmentsData(list, item.id)
if (children) {
item.children = children
}
result.push(item)
}
})
return result
}
Import method, filter the obtained data with getDepartmentsData()
Get the tableData array
import { getDepartmentsData } from '@/utils/terrData'
export default {
data () {
return {
tableData: []
}
},
methods: {
async getPermissionListApi () {
// 获取数据
const res = await getPermissionList()
console.log(res)
// 过滤获取的数据
const tableData = getDepartmentsData(res, '0')
this.tableData = tableData
console.log(this.tableData)
},
}
}