背景:新的项目使用了vue,但是ztree的数据格式是之前的,{id,name,pId…},与vue-Treeselect的格式不一致,为了兼容后端代码,所以前端数据重新生成一次。
- 引入vue-Treeselect
npm install --save @riophae/vue-treeselect
官方文档地址:https://www.vue-treeselect.cn/#basic-features
- 在页面上使用tree-select标签
<template>
<div>
<tree-select
:options="options" //数据集
placeholder="请选择..."
v-model="id"
:defaultExpandLevel='Infinity' //是否展开所有节点
:disable-branch-nodes="true" //父节点不可选择
/>
<div/>
<template/>
<script>
import TreeSelect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css' //treeselect样式,不引入的话,图标会变得很大
export default {
name: "index",
data() {
return {
id: null, //不使用null的话,输入框的提示语就会变成unknown
options: []
}
},
components: {TreeSelect},
methods: {
iniTree(queryParam){
//初始化树,iniTree是你自己写好的axios方法,这边只是举例,本文没有这个方法
iniTree(queryParam).then(data=>{
//数据转换
let tree = this.listToTree(data);
//删除children为空的参数
this.diGuiTree(tree);
this.options = tree;
});
},
listToTree(data, options) { //{id,pId,name}转成{id,label,children}类型
if (data && data.length) {
options = options || {}
let ID_KEY = options.idKey || 'id'
let PARENT_KEY = options.parentKey || 'pId'
let CHILDREN_KEY = options.childrenKey || 'children'
let tree = []
let childrenOf = {}
var item, id, parentId
for (var i = 0, length = data.length; i < length; i++) {
item = data[i]
item.label = data[i].name
id = item[ID_KEY]
parentId = item[PARENT_KEY] || 0
// 每行数据都可能存在子类
childrenOf[id] = childrenOf[id] || []
// 初始化子类
item[CHILDREN_KEY] = childrenOf[id]
if (parentId != 0) {
// 初始化其父的子节点
childrenOf[parentId] = childrenOf[parentId] || []
// 把它推到父类下的children
childrenOf[parentId].push(item)
} else {
tree.push(item)
}
}
return tree
} else {
return []
}
},
diGuiTree(item) { //递归便利树结构,删除children为空的参数
item.forEach(node => {
node.children == [] || node.children.length == 0 ? delete node.children : this.diGuiTree(node.children);
});
}
},
mounted () {
this.iniCaseReasonTree()
}
}
</script>
<style scoped>
</style>
总结:做个记录,要是忘了,以后好找