
ant-design-vue TreeSelect 树选择组件完全指南API 详解、源码实现与实战示例【免费下载链接】ant-design-vue An enterprise-class UI components based on Ant Design and Vue. 项目地址: https://gitcode.com/gh_mirrors/an/ant-design-vueTreeSelect 是 ant-design-vue 提供的树型选择控件它复用 Select 的选择交互但选项数据结构是树形的天然适合公司层级、学科系统、分类目录等层级化数据的录入场景。本文以 components/tree-select/index.zh-CN.md 为骨架结合组件源码 components/tree-select/index.tsx、官方 Demobasic.vue 等 13 个示例与单元测试系统讲解 TreeSelect 的全部 API、常用场景组合与底层实现原理帮助你从会用走向用得明白。何时使用 TreeSelectTreeSelect 与 Select 的交互方式类似点击展开下拉、输入过滤、多选打 Tag唯一区别在于选项的数据结构是树形的。当你的候选数据存在明显的层级关系时例如公司组织架构部门 → 小组 → 成员学科体系学院 → 专业 → 课程商品/内容分类目录一级分类 → 二级分类 → 叶子节点。就应当优先选用 TreeSelect它内置了父节点展开/收起、子树级联勾选、异步加载子节点等树形交互能力而普通 Select 只能平铺展示所有选项。快速上手基本用法先看官方最简示例 basic.vue它演示了v-model:value受控取值、show-search搜索、allow-clear清除、tree-default-expand-all默认展开以及treeData数据源template a-tree-select v-model:valuevalue show-search stylewidth: 100% :dropdown-style{ maxHeight: 400px, overflow: auto } placeholderPlease select allow-clear tree-default-expand-all :tree-datatreeData tree-node-filter-proplabel template #title{ value: val, label } b v-ifval parent 1-1 stylecolor: #08csss/b template v-else{{ label }}/template /template /a-tree-select /template script langts setup import { ref, watch } from vue; import type { TreeSelectProps } from ant-design-vue; const value refstring(); const treeData refTreeSelectProps[treeData]([ { label: root 1, value: root 1, children: [ { label: parent 1, value: parent 1, children: [ { label: parent 1-0, value: parent 1-0, children: [ { label: my leaf, value: leaf1 }, { label: your leaf, value: leaf2 }, ]}, { label: parent 1-1, value: parent 1-1 }, ], }, { label: parent 2, value: parent 2 }, ], }, ]); watch(value, () { console.log(value.value); }); /script要点说明v-model:value组件的受控值。在源码 index.tsx 中声明了onUpdate:value事件因此支持 Vue 3 的v-model:value语法单选时是string多选/可勾选时是string[]#title插槽自定义树节点渲染插槽参数中包含value、label、title等字段可用作高亮、图标或富文本展示tree-node-filter-proplabel指明搜索过滤时依据label字段匹配默认是value。TreeSelect 完整 API 详解TreeSelect 共提供 42 个核心属性本文按数据、选择、搜索、展开加载、外观交互五个维度分组讲解保证每个参数都给出类型、默认值与适用场景。数据配置treeData / treeDataSimpleMode / fieldNames参数说明类型默认值版本treeDatatreeNodes 数据如果设置则不需要手动构造 TreeNode 节点value 在整个树范围内唯一array{value, label, children, [disabled, disableCheckbox, selectable]}[]treeDataSimpleMode使用简单格式的 treeData此时 treeData 应为[{id:1, pId:0, value:1, label:test1,...}]pId是父节点的 id可传入对象自定义id/pId字段名false | Array{ id: string, pId: string, rootPId: null }falsefieldNames替换 treeNode 中 label、value、children 字段为 treeData 中对应的字段object{children:children, label:title, value:value}3.0.0replaceFields替换 treeNode 中 label、value、key、children 字段旧 APIobject{children:children, label:title, key:key, value:value}1.6.13.0.0 废弃treeNodeLabelProp作为显示内容的 prop 设置stringtitletreeData 是首选数据源。源码 index.tsx 在初始化时会发出警告children方式手写a-tree-select-node已废弃请改用treeDatatreeDataSimpleMode 扁平化数据当后端返回的是id/pId扁平列表时无需手动组装嵌套结构组件会自动按pId建树。异步加载示例 async.vue 即采用此模式fieldNames 适配后端字段名后端字段叫name而非title时通过:field-names{ children: children, label: name, value: value }映射完整示例见 replaceFields.vue。对应地tree-node-filter-prop也要同步改为namereplaceFields 已废弃源码 index.tsx 会打印replaceFields is deprecated, please use fieldNames instead的告警且实现上直接取fieldNames props.replaceFieldsindex.tsx兼容旧写法。选择与回填value / multiple / treeCheckable / showCheckedStrategy参数说明类型默认值版本value(v-model)指定当前选中的条目string/string[]-defaultValue指定默认选中的条目非受控string/string[]-multiple支持多选设置 treeCheckable 时自动变为 truebooleanfalsetreeCheckable显示 checkboxbooleanfalsetreeCheckStrictlycheckable 状态下节点选择完全受控父子节点选中状态不再关联会使labelInValue强制为 truebooleanfalseshowCheckedStrategy定义选中项回填方式TreeSelect.SHOW_ALL显示所有选中节点含父节点TreeSelect.SHOW_PARENT只显示父节点其下所有子节点均选中时默认只显示子节点enum{SHOW_ALL, SHOW_PARENT, SHOW_CHILD}TreeSelect.SHOW_CHILDlabelInValue是否把每个选项的 label 包装进 valuevalue 类型从string变为{value: string, label: VNode, halfChecked: string[]}booleanfalsemultiple与treeCheckable的关系源码 index.tsx 计算isMultiple !!(props.treeCheckable || props.multiple)即开启treeCheckable时多选自动生效同时会输出告警提示你无需再手动传multipleshowCheckedStrategy的用法在 checkable.vue 中通过import { TreeSelect } from ant-design-vue取TreeSelect.SHOW_PARENT用于父节点全选中时只回填父节点。这三个常量由源码 index.tsx 通过Object.assign(TreeSelect, { TreeNode, SHOW_ALL, SHOW_PARENT, SHOW_CHILD, install })静态挂载treeCheckStrictly适合父子独立勾选的场景如权限分配此时labelInValue被强制置为 true多选 Tag 的辅助参数maxTagCount最多显示 tag 数、maxTagPlaceholder隐藏 tag 时的占位内容slot/function(omittedValues)在 virtual-scroll.vue 中可以看到:max-tag-count10的实际用法。搜索与过滤showSearch / filterTreeNode / searchValue参数说明类型默认值版本showSearch在下拉中显示搜索框仅在单选模式下生效booleanfalsesearchPlaceholder搜索框默认文字string|slot-searchValue(v-model)搜索框的值可通过search事件获取用户输入string-filterTreeNode是否根据输入项进行筛选默认用 treeNodeFilterProp 的值作为要筛选的属性也可传Function(inputValue, treeNode)自定义需返回 boolboolean | FunctionFunctiontreeNodeFilterProp输入项过滤对应的 treeNode 属性stringvalue单选模式下开启show-search后下拉面板顶部会出现搜索框输入内容即时过滤树节点多选模式本身就支持输入过滤无需额外开启searchValue与search事件配合可实现搜索值的完全受控源码 index.tsx 中handleSearch同时触发update:searchValue与search即v-model:search-value可直接绑定若树节点显示文本与 value 不一致如 value 是编码、label 是名称记得将treeNodeFilterProp设为label否则按默认的value过滤可能搜不到用户想输入的中文名。展开与异步加载treeExpandedKeys / loadData / treeLoadedKeys参数说明类型默认值版本treeDefaultExpandAll默认展开所有树节点booleanfalsetreeDefaultExpandedKeys默认展开的树节点非受控string[] | number[]-treeExpandedKeys(v-model)设置展开的树节点受控string[] | number[]-loadData异步加载数据function(node)-treeLoadedKeys受控已经加载的节点需要配合loadData使用string[][]3.3.0异步加载的完整范式见 async.vue配合tree-data-simple-mode使用扁平数据onLoadData返回一个 Promise在 Promise 中请求接口并追加子节点resolve(true)通知组件展开完成const onLoadData (treeNode: TreeSelectProps[treeData][number]) { return new Promise(resolve { const { id } treeNode.dataRef; setTimeout(() { treeData.value treeData.value.concat([ genTreeNode(id, false), genTreeNode(id, true), genTreeNode(id, true), ]); resolve(true); }, 300); }); };注意loadData回调的treeNode对象需要通过treeNode.dataRef拿到原始数据包含id、isLeaf等字段叶子节点应在数据中标记isLeaf: true否则组件会一直尝试加载。外观、尺寸与交互细节参数说明类型默认值版本allowClear显示清除按钮booleanfalsedisabled是否禁用booleanfalseplaceholder选择框默认文字string|slot-size选择框大小可选largesmallstringdefaultstatus设置校验状态error | warning-3.3.0placement选择框弹出的位置bottomLeftbottomRighttopLefttopRightbottomLeft3.3.0suffixIcon自定义的选择框后缀图标VNode | slot-treeIcon是否展示 TreeNode title 前的图标无默认样式需自行定义booleanfalsetreeLine是否展示线条样式可传{ showLeafIcon }对象控制叶子图标boolean | objectfalse3.0virtual设置 false 时关闭虚拟滚动booleantrue3.0listHeight设置弹窗滚动高度number256dropdownMatchSelectWidth下拉菜单与选择器同宽默认设置min-width值小于选择框宽度时忽略false 会关闭虚拟滚动boolean | numbertruedropdownStyle下拉菜单的样式object-popupClassName下拉菜单的 classNamestring-4.0getPopupContainer菜单渲染父节点默认渲染到 body遇到菜单滚动定位问题时可改为滚动区域并相对定位Function(triggerNode)() document.bodynotFoundContent下拉列表为空时显示的内容slotNot FoundtagRender自定义 tag 内容多选时生效slot-3.0title自定义标题slot-3.0.0分组场景示例校验状态statuserror/statuswarning可直接展示红/黄边框见 status.vue。源码 index.tsx 通过getMergedStatus将 Form 表单上下文的校验状态与组件自身status合并因此放进a-form-item时会自动继承表单校验结果无需重复设置弹出方向placement支持四个方向默认bottomLeft注意源码 index.tsx 中当 ConfigProvider 配置了 RTL 方向时默认值会自动切换为bottomRight虚拟滚动virtual默认开启配合listHeight默认 256见 index.tsx 的initDefaultProps与listItemHeight默认 26渲染。当树节点数量很大数千级时建议保持开启参考 virtual-scroll.vue 中递归生成 10×10×10 级别数据量级的示例线条样式treeLine传布尔值开启连接线传对象可控制showLeafIcon见 tree-line.vue其样式语义与 Tree 组件的 showLine 一致自定义 Tag多选模式下用#tagRender插槽接管已选项标签渲染插槽参数为{ label, closable, onClose, option }custom-tag-render.vue 展示了利用option.color给不同节点 Tag 上色的做法单选场景直接使用#title插槽即可弹出容器getPopupContainer默认挂载到 body若在滚动容器内出现下拉定位异常应将其指向滚动区域并配合相对定位。事件Events事件名称说明回调参数版本change选中树节点或输入值发生变化时调用function(value, label, extra)dropdownVisibleChange展开/收起下拉菜单的回调function(open)3.0search文本框值变化时回调function(value: string)select树节点被选中时调用function(value, node, extra)treeExpand展开树节点时调用function(expandedKeys)源码 index.tsx 展示了事件转发链handleChange先触发update:value支撑 v-model再触发change最后通知FormItemContext.onFieldChange()让 Form 感知字段变化handleSearch同理同时触发update:searchValue与searchhandleTreeExpand同时触发update:treeExpandedKeys与treeExpand。这解释了为什么searchValue、treeExpandedKeys都能直接使用v-model语法。Tree 方法Methods名称描述blur()移除焦点focus()获取焦点通过模板 ref 或useTemplateRef获取组件实例后调用。源码 index.tsx 用expose({ focus, blur })显式暴露这两个方法内部委托给底层vc-tree-select的实例treeSelectRef.value.focus?.()。TreeNode props组件式节点官方建议使用treeData代替手写 TreeNode免去手工构造的麻烦。参数说明类型默认值版本checkable当树为 checkable 时设置独立节点是否展示 Checkboxboolean-disableCheckbox禁掉 checkboxbooleanfalsedisabled是否禁用booleanfalseisLeaf是否是叶子节点booleanfalsekey此项必须设置其值在整个树范围内唯一string | number-selectable是否可选booleantruetitle树节点显示的内容string|slot---value默认根据此属性值进行筛选其值在整个树范围内唯一string-这些字段同时对应treeData数组中单个节点的可选扩展属性disabled、disableCheckbox、selectable、isLeaf在 checkable.vue 中可见{ label: Child Node3, value: 0-1-0, disabled: true }的用法——树数据中直接给节点打标即可无需手动渲染组件节点。源码实现TreeSelect 是如何工作的TreeSelect 在架构上是一层薄封装核心逻辑全部下沉到内部组件库 components/vc-tree-select提供VcTreeSelect、TreeNode以及SHOW_ALL/SHOW_PARENT/SHOW_CHILD常量ant-design-vue 层负责Props 归一化在 treeSelectProps() 中从vcTreeSelectProps剔除showTreeIcon、treeMotion、inputIcon等内部细节再补充suffixIcon、size、bordered、treeLine、status、popupClassName等对外属性并通过initDefaultProps设置listHeight: 256、treeIcon: false、listItemHeight: 26、bordered: true等默认值废弃 API 告警对children节点、treeCheckable时多余的multiple、replaceFields、dropdownClassName分别输出 dev 警告index.tsx主题与上下文集成通过useConfigInject(select, props)继承 ConfigProvider 的prefixCls、size、getPopupContainer、disabled、dropdownMatchSelectWidth、virtual等全局配置结合FormItemInputContext实现表单校验联动通过useCompactItemContext支持与a-space紧凑排列组合样式体系样式基于 CSS-in-JS 实现——useSelectStyle复用 Select 的样式与useStyleTreeSelect 专属样式两个 wrapper 包裹渲染结果wrapSelectSSR/wrapTreeSelectSSR同时支持 SSR 样式抽取插槽映射将 Vue 插槽统一转换为v-slots与customSlots传给底层组件并注入默认的treeCheckable勾选框样式插槽index.tsx。组件的单元测试位于 components/tree-select/tests/index.test.js通过项目共享的focusTest验证 focus/blur 方法与mountTest验证组件可正常挂载、卸载且无副作用保证基础契约稳定快照测试见 components/tree-select/tests/snapshots/demo.test.js.snap。实践建议汇总数据量大上千节点时保持virtual开启必要时调小listHeight或通过dropdownMatchSelectWidth{false}释放滚动条空间后端扁平接口优先用tree-data-simple-modeid/pId避免前端递归组树接口字段与组件默认字段不一致用fieldNames映射并同步调整tree-node-filter-prop表单校验无需手动传status放入a-form-item后校验状态会自动联动需要手动展示时再传statuserror | warning多级勾选回填按业务语义选择SHOW_ALL完整展示或SHOW_PARENT聚合展示默认SHOW_CHILD只回填叶子异步加载叶子节点务必标记isLeaf: true并在loadData的 Promise resolve 后追加子节点数据。如需查看更多场景可直接阅读 components/tree-select/demo 目录下的全部 13 个示例含 placement.vue、suffix.vue、highlight.vue每个示例都是可直接复制运行的 Vue 3 SFC。【免费下载链接】ant-design-vue An enterprise-class UI components based on Ant Design and Vue. 项目地址: https://gitcode.com/gh_mirrors/an/ant-design-vue创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考