官网地址:https://www.npmjs.com/package/@riophae/vue-treeselect
是3年前更新的
安装:
cnpm install --save @riophae/vue-treeselect
如果你的项目是vue3的话,使用该安装命令会提示,此命令只针对vue2.2版本
具体提示内容是:
peerDependencies WARNING @riophae/vue-treeselect@latest requires a peer of vue@^2.2.0 but [email protected] was installed
结果:
"@riophae/vue-treeselect": "^0.4.0",
引入
import Treeselect from '@riophae/vue-treeselect'
官网地址:https://www.npmjs.com/package/vue3-treeselect
vue中的官网:https://www.vue-treeselect.cn/
安装:
npm install --save vue3-treeselect
结果
"dependencies": {
"vue": "^3.2.25",
"vue3-treeselect": "^0.1.10"
},
在vue页面中适用树形选择组件
<treeselect v-model="state.JCJGCity" :multiple="true" :options="state.cityTreeData"
:normalizer="state.normalizer" placeholder="默认所有"
style="width: 50%;">
</treeselect>
// import the component
import Treeselect from 'vue3-treeselect'
// import the styles
import 'vue3-treeselect/dist/vue3-treeselect.css'
注
此处的cityTreeData为后端返回的数据,由于 vue3-treeselect 插件适用的数据格式是:id、label、children
options: [
{id: 'a',label: 'a',
children: [
{id: 'aa',label: 'aa'}
{id: 'ab',label: 'ab'} ],
},
{id: 'b',label: 'b'},
{id: 'c',label: 'c'}
],
而后台给的数据肯定字段名与要求不太一致:
因此,需要把后台数据格式适配成与 vue3-treeselect 一致的数据,此时适用内置的 :normalizer=“state.normalizer” 属性即可
const state = reactive({
cityTreeData: [],
JCJGCity:null,
normalizer(node){
if (node.childList && !node.childList.length) { //去掉childList=[]的情况
delete node.childList;
}
return {
id: node.id, //字段名的替换
label: node.name,
children: node.childList
}
},
})
这样,就已经实现可搜索,可多选的功能了
Name | 属性 | 描述 |
---|---|---|
open | (instanceId) | 菜单打开时发出 |
close | (value, instanceId) | 菜单关闭时发出 |
input | (value, instanceId) | 值更改后发出 |
select | (node, instanceId) | 选择一个选项后发出 |
deselect | (node, instanceId) | 取消选择一个选项后发出 |
search-change | (searchQuery, instanceId) | 搜索查询更改后发出 |
如果项目使用的element-plus组件库,此方法更好用
<el-tree-select
v-model="value"
:data="data"
:render-after-expand="false"
show-checkbox
/>
<el-tree-select
v-model="state.JCJGID"
:data="state.cityTreeData"
:render-after-expand="false" check-strictly
:props="defaultProps"
placeholder="请选择,默认为所有检察机关"
clearable filterable accordion
style="width:100%"
@change="changeJCJGID()"
/>