今天在项目中想要实现一个树形下拉框的效果,找了下资料,发现插件 vue-treeselect 可以实现这个效果。
vue-treeselect官网
Github地址
vue-treeselect 的用法:
首先,通过 npm 安装 vue-treeselect:
npm install --save @riophae/vue-treeselect
接下来,就可以使用了。
vue-treeselect 要求的填充数据格式如下:
{
id: '' ,
label: ',
children: [
{
id: '' ,
label: '' ,
},
...
],
}
后台返回的数据格式如下:
{
"id": "1",
"idxno": 1,
"name": "123",
"desc": "123",
"children": [
{
"id": "12",
"idxno": 0,
"name": "45",
"desc": "45",
"children": []
},
{
"id": "dev",
"idxno": 2,
"name": "dev",
"desc": "111",
"children": [
{
"id": "14",
"idxno": 0,
"name": "12",
"desc": "12",
"children": []
},
{
"id": "13",
"idxno": 0,
"name": "qwer",
"desc": "qweee",
"children": []
}
]
},
{
"id": "2",
"idxno": 3,
"name": "test",
"desc": "test",
"children": []
}
]
}
实现过程如下:
<el-form-item
:label="$t('sysManage.department.table.parDepart')">
<treeselect
:options="preDepartTreeData"
:normalizer="normalizer"
v-model="oneDepart.parentId"
:placeholder="$t('sysManage.department.parDepartInput')"
></treeselect>
</el-form-item>
<script>
// import the component
import Treeselect from "@riophae/vue-treeselect";
// import the styles
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { truncate } from 'fs';
export default {
components: {
Treeselect
},
data() {
return {
oneDepart: Object.assign({}, defaultDepart),
preDepartTreeData: []
],
// 后台返回的数据和VueTreeselect要求的数据结构不同,需要进行转换
normalizer(node) {
//去掉children=[]的children属性
if (node.children && !node.children.length) {
delete node.children;
}
return {
id: node.id,
label: node.name,
children: node.children
}
}
}
}
};
</script>
options的值是树形结构的数组;
normalizer属性,用于转换options的值,把options的值,转换为符合vue-treeselect要求的数据格式。