根据后台给一组id回显可选择的选项列表
<template>
<div>
<el-cascader
:key="keyValue"
ref="cascader"
v-model="pids"
:props="{ label: 'name', value: 'id' }"
:options="options"
clearable
filterable
@change="handleChange"
/>
<button @click="clickHandle">回显[3,4,10]</button>
</div>
</template>
<script>
export default {
name: 'QualityClassify',
data() {
return {
keyValue: 0,
pids: [],
options: [],
defaultOptions: [
{
id: 1,
name: '总部id1',
children: [
{
id: 2,
name: '工程技术部id2',
parent_id: 1,
children: [
{ id: 3, name: '工程员工id3', parent_id: 2 },
{ id: 4, name: '工程员工id4', parent_id: 2 },
{ id: 5, name: '工程员工id45', parent_id: 2 }
]
},
{
id: 7,
name: '人力资源id7',
parent_id: 1,
children: [
{ id: 8, name: '人力员工id8', parent_id: 7 },
{ id: 9, name: '人力员工id9', parent_id: 7 },
{ id: 10, name: '人力员工id10', parent_id: 7 }
]
}
]
}
],
defaultArr: [[1, 2, 3], [1, 2, 4], [1, 7, 10]]
}
},
watch: {
options() {
this.keyValue++
}
},
methods: {
handleChange(value) {
console.log('value', value)
},
// 删除children为空
deleteChildren(arr) {
return arr.map(item => {
if (item.children && item.children.length > 0) {
this.deleteChildren(item.children)
} else {
delete item.children
}
return item
})
},
clickHandle() {
const list = []
this.findParentChild(this.defaultOptions, this.defaultArr, list)
this.options = this.deleteChildren(list)
},
// 根据id数组查找对应的对象数组
findParentChild(list, str, arr) {
list.map(v => {
str.map(s => {
s.filter(x => {
if (x === v.id) {
if ((!v.parent_id || v.parent_id !== '0') && arr.length > 0) {
this.findChild(v, arr, str)
} else {
const isHas = arr.findIndex(x => x.id === v.id)
if (isHas === -1) {
arr.push({
...v,
children: []
})
}
}
} else {
if (v.children && v.children.length) {
this.findParentChild(v.children, str, arr)
} else {
return false
}
}
})
})
})
},
// 查找最终列表父级的children,并往里塞对象
findChild(obj, arr, str) {
arr.map(v => {
if (v.children && v.children.length > 0) {
const isHas = v.children.findIndex(x => x.id === obj.id)
if (isHas === -1 && obj.parent_id === v.id) {
v.children.push({
...obj,
children: []
})
} else if (obj.children) this.findParentChild(obj.children, str, v.children)
} else {
if (obj.parent_id === v.id) {
v.children.push({
...obj,
children: []
})
if (obj.children) this.findParentChild(obj.children, str, v.children)
}
}
})
}
}
}
</script>