Cascader-单选模式,实现末级子数据回显(类似:热门标签)
实现效果
展示代码
页面
<el-cascader ref="Cascader1" v-model="value" :options="options" :props="{label:'name',value:'id'}"
@change="handleChange" @visible-change="qdVisibleChange" clearable>
</el-cascader>
数据
data () {
return {
value: [],
options: [
{
id: '1',
name: '北京1',
children: [{
id: '1-1',
pid: '1',
name: '北京1-1',
children: [{
id: '1-1-1',
pid: '1-1',
name: '北京1-1-1',
},
{
id: '1-1-2',
pid: '1-1',
name: '北京1-1-2',
},
{
id: '1-1-3',
pid: '1-1',
name: '北京1-1-3',
}]
}, {
id: '1-2',
pid: '1',
name: '北京2-1',
children: [{
id: '1-2-1',
pid: '1-2',
name: '北京1-2-1',
},
{
id: '1-2-2',
pid: '1-2',
name: '北京1-2-2',
},
{
id: '1-2-3',
pid: '1-2',
name: '北京1-2-3',
}]
}]
}
],
childList: [
{
id: '1-2-1',
pid: '1-2',
name: '北京1-2-1',
},
{
id: '1-2-2',
pid: '1-2',
name: '北京1-2-2',
},
{
id: '1-2-3',
pid: '1-2',
name: '北京1-2-3',
}
]
}
}
方法
methods: {
// 树查询:通过子id获取所有父节点
getTreeParent (treeData, searchId, parentAttr = 'parentid', childAttr = 'sid') {
var arrRes = [];
if (treeData.length == 0) {
if (!!searchId) {
arrRes.unshift(treeData)
}
return arrRes;
}
let rev = (data, nodeId) => {
for (var i = 0, length = data.length; i < length; i++) {
let node = data[i];
if (node[childAttr] == nodeId) {
arrRes.unshift(node)
rev(treeData, node[parentAttr])
break;
}
else {
if (!!node.children) {
rev(node.children, nodeId);
}
}
}
return arrRes;
};
arrRes = rev(treeData, searchId)
arrRes = arrRes.map(v => v[childAttr])
return arrRes;
},
handleChange (value) {
console.log(value)
},
// 下拉回显展示的值
qdVisibleChange (val) {
if (!val) {
if (this.$refs['Cascader1']) {
this.$refs['Cascader1'].$refs.panel.activePath = []
}
} else {
if (this.$refs['Cascader1']) {
this.$refs['Cascader1'].$refs.panel.initStore()
}
}
},
// 子数据回显
remenTagHandle (item) {
let list = this.getTreeParent(this.options, item.id, 'pid', 'id')
this.value = [...list]
if (this.$refs.qudaoCascader) {
this.$refs.qudaoCascader.$refs.panel.activePath = []
this.$refs.qudaoCascader.$refs.panel.calculateCheckedNodePaths()
}
},
}