Skip to content

TreeSelect 树选择

树型选择控件。

代码演示

基础用法

vue
<template>
  <a-tree-select
    v-model:value="value"
    show-search
    style="width: 100%"
    :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
    placeholder="Please select"
    allow-clear
    tree-default-expand-all
    :tree-data="treeData"
    tree-node-filter-prop="label"
  >
    <template #title="{ value: val, label }">
      <b v-if="val === 'parent 1-1'" style="color: #08c">sss</b>
      <template v-else>{{ label }}</template>
    </template>
  </a-tree-select>
</template>
<script setup>
import { ref, watch } from 'vue';
const value = ref();
const treeData = ref([
  {
    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>

多选

vue
<template>
  <a-tree-select
    v-model:value="value"
    show-search
    style="width: 100%"
    :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
    placeholder="Please select"
    allow-clear
    multiple
    tree-default-expand-all
    :tree-data="treeData"
    tree-node-filter-prop="label"
  >
    <template #title="{ value: val, label }">
      <b v-if="val === 'parent 1-1'" style="color: #08c">{{ val }}</b>
      <template v-else>{{ label }}</template>
    </template>
  </a-tree-select>
</template>
<script setup>
import { ref, watch } from 'vue';
const value = ref([]);
const treeData = ref([
  {
    label: 'parent 1',
    value: 'parent 1',
    children: [
      {
        label: 'parent 1-0',
        value: 'parent 1-0',
        children: [
          {
            label: 'parent 1-0-0',
            value: 'parent 1-0-0',
            children: [
              {
                label: 'my leaf',
                value: 'leaf1',
              },
              {
                label: 'your leaf',
                value: 'leaf2',
              },
            ],
          },
          {
            label: 'parent 1-0-1',
            value: 'parent 1-0-1',
          },
        ],
      },
      {
        label: 'parent 1-1',
        value: 'parent 1-1',
      },
    ],
  },
]);
watch(value, () => {
  console.log('select', value.value);
});
</script>

可勾选

使用勾选框实现多选功能。

vue
<template>
  <a-tree-select
    v-model:value="value2"
    style="width: 100%"
    :tree-data="treeData2"
    tree-checkable
    allow-clear
    :show-checked-strategy="SHOW_PARENT"
    placeholder="Please select"
    tree-node-filter-prop="label"
  />
</template>
<script setup>
import { ref, watch } from 'vue';
import { TreeSelect } from 'ant-design-vue';
const SHOW_PARENT = TreeSelect.SHOW_PARENT;
const treeData = [
  {
    label: 'Node1',
    value: '0-0',
    children: [
      {
        label: 'Child Node1',
        value: '0-0-0',
      },
    ],
  },
  {
    label: 'Node2',
    value: '0-1',
    children: [
      {
        label: 'Child Node3',
        value: '0-1-0',
        disabled: true,
      },
      {
        label: 'Child Node4',
        value: '0-1-1',
      },
      {
        label: 'Child Node5',
        value: '0-1-2',
      },
    ],
  },
];
const value = ref(['0-0-0']);
watch(value, () => {
  console.log(value.value);
});
</script>

异步加载

异步加载树节点。

Please select
vue
<template>
  <a-tree-select
    v-model:value="value"
    tree-data-simple-mode
    style="width: 100%"
    :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
    :tree-data="treeData"
    placeholder="Please select"
    :load-data="onLoadData"
  />
</template>
<script setup>
import { ref, watch } from 'vue';
const value = ref();
const treeData = ref([
  {
    id: 1,
    pId: 0,
    value: '1',
    title: 'Expand to load',
  },
  {
    id: 2,
    pId: 0,
    value: '2',
    title: 'Expand to load',
  },
  {
    id: 3,
    pId: 0,
    value: '3',
    title: 'Tree Node',
    isLeaf: true,
  },
]);
watch(value, () => {
  console.log(value.value);
});
const genTreeNode = (parentId, isLeaf = false) => {
  const random = Math.random().toString(36).substring(2, 6);
  return {
    id: random,
    pId: parentId,
    value: random,
    title: isLeaf ? 'Tree Node' : 'Expand to load',
    isLeaf,
  };
};
const onLoadData = treeNode => {
  return new Promise(resolve => {
    const { id } = treeNode.dataRef;
    setTimeout(() => {
      treeData.value = treeData.value.concat([
        genTreeNode(id, false),
        genTreeNode(id, true),
        genTreeNode(id, true),
      ]);
      console.log(treeData.value);
      resolve(true);
    }, 300);
  });
};
</script>

虚拟滚动

使用 height 属性则切换为虚拟滚动。

vue
<template>
  <a-tree-select
    v-model:value="checkedKeys"
    style="width: 100%"
    tree-checkable
    tree-default-expand-all
    :show-checked-strategy="SHOW_PARENT"
    :height="233"
    :tree-data="treeData"
    :max-tag-count="10"
    tree-node-filter-prop="title"
  >
    <template #title="{ title, value }">
      <span v-if="value === '0-0-1-0'" style="color: #1890ff">{{ title }}</span>
      <template v-else>{{ title }}</template>
    </template>
  </a-tree-select>
</template>
<script setup>
import { ref, watch } from 'vue';
import { TreeSelect } from 'ant-design-vue';
const SHOW_PARENT = TreeSelect.SHOW_PARENT;
function dig(path = '0', level = 3) {
  const list = [];
  for (let i = 0; i < 10; i += 1) {
    const value = `${path}-${i}`;
    const treeNode = {
      title: value,
      value,
    };
    if (level > 0) {
      treeNode.children = dig(value, level - 1);
    }
    list.push(treeNode);
  }
  return list;
}
const checkedKeys = ref(['0-0-0', '0-0-1']);
watch(checkedKeys, () => {
  console.log('checkedKeys', checkedKeys);
});
const treeData = ref(dig());
</script>

自定义选择标签

允许自定义选择标签的样式。仅支持多选模式,单选可直接使用 title 插槽

vue
<template>
  <a-tree-select
    v-model:value="value"
    show-search
    style="width: 100%"
    :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
    placeholder="Please select"
    allow-clear
    multiple
    :show-checked-strategy="SHOW_ALL"
    tree-default-expand-all
    :tree-data="treeData"
    tree-node-filter-prop="label"
  >
    <template #tagRender="{ label, closable, onClose, option }">
      <a-tag :closable="closable" :color="option.color" style="margin-right: 3px" @close="onClose">
        {{ label }}&nbsp;&nbsp;
      </a-tag>
    </template>
    <template #title="{ value: val, label }">
      <b v-if="val === 'parent 1-1'" style="color: #08c">{{ val }}</b>
      <template v-else>{{ label }}</template>
    </template>
  </a-tree-select>
</template>
<script setup>
import { ref, watch } from 'vue';
import { TreeSelect } from 'ant-design-vue';
const SHOW_ALL = TreeSelect.SHOW_ALL;
const value = ref(['parent 1', 'parent 1-0', 'leaf1']);
const treeData = ref([
  {
    label: 'parent 1',
    value: 'parent 1',
    color: 'pink',
    children: [
      {
        label: 'parent 1-0',
        value: 'parent 1-0',
        color: 'pink',
        children: [
          {
            label: 'parent 1-0-0',
            value: 'parent 1-0-0',
            color: 'orange',
            children: [
              {
                label: 'my leaf',
                value: 'leaf1',
                color: 'green',
              },
              {
                label: 'your leaf',
                value: 'leaf2',
                color: 'cyan',
              },
            ],
          },
          {
            label: 'parent 1-0-1',
            value: 'parent 1-0-1',
            color: 'blue',
          },
        ],
      },
      {
        label: 'parent 1-1',
        value: 'parent 1-1',
        color: 'blue',
      },
    ],
  },
]);
watch(value, () => {
  console.log('select', value.value);
});
</script>

自定义状态

使用 status 为 DatePicker 添加状态,可选 error 或者 warning

Error
vue
<template>
  <a-space direction="vertical" style="width: 100%">
    <a-tree-select status="error" style="width: 100%" placeholder="Error" />
    <a-tree-select status="warning" style="width: 100%" multiple placeholder="Warning multiple" />
  </a-space>
</template>

API

Tree props

参数说明类型默认值
allowClear显示清除按钮booleanfalse
defaultValue指定默认选中的条目string/string[]-
disabled是否禁用booleanfalse
popupClassName下拉菜单的className 属性string
dropdownMatchSelectWidth下拉菜单和选择器同宽。默认将设置 min-width,当值小于选择框宽度时会被忽略。false 时会关闭虚拟滚动boolean | numbertrue
dropdownStyle下拉菜单的样式object-
fieldNames替换 treeNode 中 label,value,children 字段为 treeData 中对应的字段object{children:'children', label:'title', value: 'value' }
filterTreeNode是否根据输入项进行筛选,默认用 treeNodeFilterProp 的值作为要筛选的 TreeNode 的属性值boolean | Function(inputValue: string, treeNode: TreeNode) (函数需要返回 bool 值)Function
getPopupContainer菜单渲染父节点。默认渲染到 body 上,如果你遇到菜单滚动定位问题,试试修改为滚动的区域,并相对其定位。Function(triggerNode)() => document.body
labelInValue是否把每个选项的 label 包装到 value 中,会把 value 类型从 string 变为 {value: string, label: VNode, halfChecked(treeCheckStrictly 时有效): string[] } 的格式booleanfalse
listHeight设置弹窗滚动高度number256
loadData异步加载数据function(node)-
maxTagCount最多显示多少个 tagnumber-
maxTagPlaceholder隐藏 tag 时显示的内容slot/function(omittedValues)-
multiple支持多选(当设置 treeCheckable 时自动变为 true)booleanfalse
notFoundContent当下拉列表为空时显示的内容slotNot Found
placeholder选择框默认文字string | slot-
placement选择框弹出的位置bottomLeft bottomRight topLeft topRightbottomLeft
replaceFields替换 treeNode 中 label,value,key,children 字段为 treeData 中对应的字段object{children:'children', label:'title', key:'key', value: 'value' }
searchPlaceholder搜索框默认文字string | slot-
searchValue(v-model)搜索框的值,可以通过 search 事件获取用户输入string-
showCheckedStrategy定义选中项回填的方式。TreeSelect.SHOW_ALL: 显示所有选中节点(包括父节点). TreeSelect.SHOW_PARENT: 只显示父节点(当父节点下所有子节点都选中时). 默认只显示子节点.enum {TreeSelect.SHOW_ALL, TreeSelect.SHOW_PARENT, TreeSelect.SHOW_CHILD }TreeSelect.SHOW_CHILD
showSearch在下拉中显示搜索框(仅在单选模式下生效)booleanfalse
size选择框大小,可选 large smallstring'default'
status设置校验状态'error' | 'warning'-
suffixIcon自定义的选择框后缀图标VNode | slot-
tagRender自定义 tag 内容,多选时生效slot-
title自定义标题slot
treeCheckable显示 checkboxbooleanfalse
treeCheckStrictlycheckable 状态下节点选择完全受控(父子节点选中状态不再关联),会使得 labelInValue 强制为 truebooleanfalse
treeDatatreeNodes 数据,如果设置则不需要手动构造 TreeNode 节点(value 在整个树范围内唯一)array<{value, label, children, [disabled, disableCheckbox, selectable]}>[]
treeDataSimpleMode使用简单格式的 treeData,具体设置参考可设置的类型 (此时 treeData 应变为这样的数据结构: [{id:1, pId:0, value:'1', label:"test1",...},...], pId 是父节点的 id)false | Array<{ id: string, pId: string, rootPId: null }>false
treeDefaultExpandAll默认展开所有树节点booleanfalse
treeDefaultExpandedKeys默认展开的树节点string[] | number[]-
treeExpandedKeys(v-model)设置展开的树节点string[] | number[]-
treeIcon是否展示 TreeNode title 前的图标,没有默认样式,如设置为 true,需要自行定义图标相关样式booleanfalse
treeLine是否展示线条样式,boolean | objectfalse
treeLoadedKeys(受控)已经加载的节点,需要配合 loadData 使用string[][]
treeNodeFilterProp输入项过滤对应的 treeNode 属性string'value'
treeNodeLabelProp作为显示的 prop 设置string'title'
value(v-model)指定当前选中的条目string/string[]-
virtual设置 false 时关闭虚拟滚动booleantrue

事件

事件名称说明回调参数
change选中树节点或输入值发生变化时调用此函数function(value, label, extra)
dropdownVisibleChange展开下拉菜单的回调function(open)
search文本框值变化时回调function(value: string)
select树节点被选中时调用function(value, node, extra)
treeExpand展开树节点时调用function(expandedKeys)

Tree 方法

名称描述
blur()移除焦点
focus()获取焦点

TreeNode props

建议使用 treeData 来代替 TreeNode,免去手工构造麻烦

参数说明类型默认值
checkable当树为 checkable 时,设置独立节点是否展示Checkboxboolean
disableCheckbox禁掉 checkboxbooleanfalse
disabled是否禁用booleanfalse
isLeaf是否是叶子节点booleanfalse
key此项必须设置(其值在整个树范围内唯一)string | number-
selectable是否可选booleantrue
title树节点显示的内容string | slot'---'
value默认根据此属性值进行筛选(其值在整个树范围内唯一)string-