显示效果如下:
使用方式:
1.先安装
npm install --save '@riophae/vue-treeselect'
2.组件中引入
// import the component
import Treeselect from "@riophae/vue-treeselect";
// import the styles
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
3.组件注册
components: { Treeselect },
4.使用组件
<treeselect
v-model="orgId"
:multiple="false"//是否多选
:clearable="fasle"//是否使用清空功能
:async="false"
:default-expand-level="1"//默认展开第1级菜单,数值越大展开的层级越多
:is-disabled="false"//
:searchable="false"//是否启用搜索,true为启用
placeholder=""
:normalizer="normalizer"//数据初始化
:options="orgOptions" //数据option
@input="handleNodeClick"//当文本框值改变时执行,类似el-select @change
@open="handleOpen" //当文本框获取焦点打开时执行
/>
5.接口数据格式
组件需要数据格式:
//若封装组件需要传入,如业务不需要从页面传option,可从此页面单独调用接口赋值orgOption
orgOption:{
type: Array,
default:()=>{
return []
}
}
orgValue:{
type: String,
default: ()=>{
return null //注:当默认值为null或者存在可匹配默认值时,组件不会显示(unknown)
}
}
6.封装方法数据初始化数据格式
normalizer(node) {
// 去掉children=[]的children属性
if (node.children && !node.children.length) {
delete node.children;
}
return {
id: node.id,
label: node.name,
children: node.children,
isDisabled: node.isDisabled,//可省略
};
},
//绑定值改变时触发
handleNodeClick(e){
this.$emit('handleNodeClick', e)//往父组件传orgValue
}
//解决与el-select不兼容问题,打开el-select组件后点vue-treeSelect无法关闭el-select > option
handleOpen(){
this.$emit('handleOpen');
}
父组件中:
<TreeSelectComponents :org-value="orgValue?orgValue:null" :org-option="orgOption" @getValue="getValue" @handleOpen="handleOpen" >
//其他el-select
<el-select ref="upSelect0" v-model="value0">option0</el-select>
<el-select ref="upSelect1" v-model="value1">option1</el-select>
<el-select ref="upSelect2" v-model="value2">option2</el-select>
<el-select ref="upSelect3" v-model="value3">option3</el-select>
<el-select ref="upSelect4" v-model="value4">option4</el-select>
methods:{
getValue(v){
console.log(v)
}
//当vue-treeSelect组件打开时,关闭其他所有el-select
handleOpen(){
for (var i=0; i<5; i++) {
this.$ref.['upSelect' + i].blur()
}
}
}
7.内网开发需往node_modules中拷入以下文件,并在package.json中注册组件
“dependencies”: {
"@riophae/vue-treeselect": "^0.4.0"
}
8.参考文章
Vue-Treeselect | Vue-Treeselect 中文网
9.以上为具体功能实现方式,另有两个问题暂未解决,一是vue-treeSelect三角标是否可替换,二是只能点击角标展开下拉框。el-select这两点都方便处理,有办法的朋友望留言赐教