Cascader 级联选择器
从有层级关系的数据里逐级选择,例如省 / 市 / 区、部门 / 小组。层级不深、每级选项不多时使用;层级很深或者需要同时看到整棵树时用 NsTreeSelect。
引入
import { NsCascader } from '@ns/ui'
基础用法
options 传层级数据,v-model 绑定的是从第一级到选中节点的路径(每一级的 value 组成的数组)。默认只能选最后一级,选中后下拉层关闭,输入框里显示完整路径。没有选中时显示 placeholder(默认“请选择”)。
<script setup lang="ts">
import { ref } from 'vue'
import { NsCascader, NsSpace } from '@ns/ui'
import type { CascaderOption } from '@ns/ui'
const value = ref<(string | number)[]>()
const other = ref<(string | number)[]>()
const options: CascaderOption[] = [
{
value: 'beijing',
label: '北京',
children: [
{
value: 'haidian',
label: '海淀区',
children: [
{ value: 'zhongguancun', label: '中关村' },
{ value: 'wudaokou', label: '五道口' }
]
},
{ value: 'dongcheng', label: '东城区' }
]
},
{
value: 'guangzhou',
label: '广州',
children: [
{ value: 'tianhe', label: '天河区' },
{ value: 'yuexiu', label: '越秀区' }
]
}
]
</script>
<template>
<!-- 选中“五道口”后 value 是 ['beijing', 'haidian', 'wudaokou'] -->
<NsSpace direction="vertical" align="start">
<NsSpace wrap>
<NsCascader v-model="value" :options="options" style="width: 260px" />
<NsCascader
v-model="other"
:options="options"
placeholder="请选择所在地区"
style="width: 260px"
/>
</NsSpace>
<span>选中的值:{{ value ? JSON.stringify(value) : 'undefined' }}</span>
</NsSpace>
</template>
展开方式
trigger 决定怎样展开下一级:click(默认)是点击节点展开,hover 是鼠标移到节点上就展开,选中仍然需要点击。expand-trigger 和 trigger 是同一个意思,两个都传时以 expand-trigger 为准。
<script setup lang="ts">
import { ref } from 'vue'
import { NsCascader, NsSpace } from '@ns/ui'
import type { CascaderOption } from '@ns/ui'
const value = ref<(string | number)[]>()
const hoverValue = ref<(string | number)[]>()
const options: CascaderOption[] = [
{
value: 'beijing',
label: '北京',
children: [
{
value: 'haidian',
label: '海淀区',
children: [
{ value: 'zhongguancun', label: '中关村' },
{ value: 'wudaokou', label: '五道口' }
]
},
{ value: 'dongcheng', label: '东城区' }
]
},
{
value: 'guangzhou',
label: '广州',
children: [
{ value: 'tianhe', label: '天河区' },
{ value: 'yuexiu', label: '越秀区' }
]
}
]
</script>
<template>
<NsSpace wrap>
<NsCascader
v-model="value"
:options="options"
trigger="click"
placeholder="点击展开(click)"
style="width: 260px"
/>
<NsCascader
v-model="hoverValue"
:options="options"
trigger="hover"
placeholder="悬停展开(hover)"
style="width: 260px"
/>
</NsSpace>
</template>
只显示最后一级
show-all-levels 默认是 true,输入框和多选标签里显示完整路径。:show-all-levels="false" 时只显示选中节点自己的文字。绑定值不受影响,仍然是完整路径。上面一行是默认,下面一行是 false:
<script setup lang="ts">
import { ref } from 'vue'
import { NsCascader, NsSpace } from '@ns/ui'
import type { CascaderOption } from '@ns/ui'
const value = ref<(string | number)[]>(['beijing', 'haidian', 'wudaokou'])
const values = ref<(string | number)[][]>([
['beijing', 'haidian', 'wudaokou'],
['guangzhou', 'tianhe']
])
const options: CascaderOption[] = [
{
value: 'beijing',
label: '北京',
children: [
{
value: 'haidian',
label: '海淀区',
children: [
{ value: 'zhongguancun', label: '中关村' },
{ value: 'wudaokou', label: '五道口' }
]
},
{ value: 'dongcheng', label: '东城区' }
]
},
{
value: 'guangzhou',
label: '广州',
children: [
{ value: 'tianhe', label: '天河区' },
{ value: 'yuexiu', label: '越秀区' }
]
}
]
</script>
<template>
<NsSpace direction="vertical" align="start">
<NsSpace wrap>
<span class="row-label">true</span>
<NsCascader v-model="value" :options="options" style="width: 220px" />
<NsCascader v-model="values" :options="options" multiple style="width: 320px" />
</NsSpace>
<NsSpace wrap>
<span class="row-label">false</span>
<NsCascader
v-model="value"
:options="options"
:show-all-levels="false"
style="width: 220px"
/>
<NsCascader
v-model="values"
:options="options"
multiple
:show-all-levels="false"
style="width: 320px"
/>
</NsSpace>
</NsSpace>
</template>
<style scoped>
.row-label {
display: inline-block;
width: 56px;
color: var(--ns-text-color-secondary);
font-size: var(--ns-font-size-sm);
}
</style>
自定义分隔符
separator 设置路径里各级文字之间的分隔符,默认是 /,前后不带空格。输入框、多选标签和搜索结果里的路径都用它。需要空格时写在分隔符里,例如 ' / '。
<script setup lang="ts">
import { ref } from 'vue'
import { NsCascader, NsSpace } from '@ns/ui'
import type { CascaderOption } from '@ns/ui'
const value = ref<(string | number)[]>(['beijing', 'haidian', 'wudaokou'])
const options: CascaderOption[] = [
{
value: 'beijing',
label: '北京',
children: [
{
value: 'haidian',
label: '海淀区',
children: [
{ value: 'zhongguancun', label: '中关村' },
{ value: 'wudaokou', label: '五道口' }
]
},
{ value: 'dongcheng', label: '东城区' }
]
},
{
value: 'guangzhou',
label: '广州',
children: [
{ value: 'tianhe', label: '天河区' },
{ value: 'yuexiu', label: '越秀区' }
]
}
]
</script>
<template>
<NsSpace direction="vertical" align="start">
<NsSpace wrap>
<span class="row-label">'/'</span>
<NsCascader v-model="value" :options="options" style="width: 260px" />
</NsSpace>
<NsSpace wrap>
<span class="row-label">' / '</span>
<NsCascader v-model="value" :options="options" separator=" / " style="width: 260px" />
</NsSpace>
<NsSpace wrap>
<span class="row-label">' > '</span>
<NsCascader v-model="value" :options="options" separator=" > " style="width: 260px" />
</NsSpace>
<NsSpace wrap>
<span class="row-label">'-'</span>
<NsCascader v-model="value" :options="options" separator="-" style="width: 260px" />
</NsSpace>
</NsSpace>
</template>
<style scoped>
.row-label {
display: inline-block;
width: 56px;
color: var(--ns-text-color-secondary);
font-size: var(--ns-font-size-sm);
white-space: pre;
}
</style>
可清空
加上 clearable 后,有值时右侧显示清除按钮(没值或禁用时不显示)。点击后单选的值变成 undefined,多选的值变成 []。
<script setup lang="ts">
import { ref } from 'vue'
import { NsCascader, NsSpace } from '@ns/ui'
import type { CascaderOption } from '@ns/ui'
const value = ref<(string | number)[]>(['beijing', 'haidian', 'wudaokou'])
const values = ref<(string | number)[][]>([['guangzhou', 'tianhe']])
const options: CascaderOption[] = [
{
value: 'beijing',
label: '北京',
children: [
{
value: 'haidian',
label: '海淀区',
children: [
{ value: 'zhongguancun', label: '中关村' },
{ value: 'wudaokou', label: '五道口' }
]
},
{ value: 'dongcheng', label: '东城区' }
]
},
{
value: 'guangzhou',
label: '广州',
children: [
{ value: 'tianhe', label: '天河区' },
{ value: 'yuexiu', label: '越秀区' }
]
}
]
</script>
<template>
<NsSpace wrap>
<NsCascader v-model="value" :options="options" clearable style="width: 260px" />
<NsCascader v-model="values" :options="options" multiple clearable style="width: 320px" />
</NsSpace>
<p style="margin-top: 12px">
单选:{{ value ? JSON.stringify(value) : 'undefined' }};多选:{{ JSON.stringify(values) }}
</p>
</template>
禁用
disabled 禁用整个选择器:不能展开,有值时也不显示清除按钮,多选的标签上没有叉。选项数据里的 disabled: true 禁用这个节点:它不能选也不能展开,所以它下面的节点也都选不到;多选时勾选父节点也不会勾上它。
<script setup lang="ts">
import { ref } from 'vue'
import { NsCascader, NsSpace } from '@ns/ui'
import type { CascaderOption } from '@ns/ui'
const empty = ref<(string | number)[]>()
const single = ref<(string | number)[]>(['beijing', 'haidian'])
const multi = ref<(string | number)[][]>([
['beijing', 'haidian'],
['beijing', 'dongcheng']
])
const value = ref<(string | number)[]>()
const values = ref<(string | number)[][]>([])
const options: CascaderOption[] = [
{
value: 'beijing',
label: '北京',
children: [
{ value: 'haidian', label: '海淀区' },
{ value: 'chaoyang', label: '朝阳区(禁用)', disabled: true },
{ value: 'dongcheng', label: '东城区' }
]
},
{ value: 'shanghai', label: '上海(禁用)', disabled: true }
]
</script>
<template>
<NsSpace direction="vertical" align="start">
<NsSpace wrap>
<span class="row-label">整体禁用</span>
<NsCascader v-model="empty" :options="options" disabled style="width: 200px" />
<NsCascader v-model="single" :options="options" disabled clearable style="width: 200px" />
<NsCascader v-model="multi" :options="options" multiple disabled style="width: 300px" />
</NsSpace>
<NsSpace wrap>
<span class="row-label">选项禁用</span>
<NsCascader v-model="value" :options="options" style="width: 200px" />
<NsCascader v-model="values" :options="options" multiple style="width: 300px" />
</NsSpace>
</NsSpace>
</template>
<style scoped>
.row-label {
display: inline-block;
width: 56px;
color: var(--ns-text-color-secondary);
font-size: var(--ns-font-size-sm);
}
</style>
可选任意一级
加上 check-strictly 后每一级都可以选。点还有下一级的节点会选中它并展开下一级,下拉层不关闭;点到最后一级才关闭。
<script setup lang="ts">
import { ref } from 'vue'
import { NsCascader } from '@ns/ui'
import type { CascaderOption } from '@ns/ui'
const value = ref<(string | number)[]>()
const options: CascaderOption[] = [
{
value: 'beijing',
label: '北京',
children: [
{
value: 'haidian',
label: '海淀区',
children: [
{ value: 'zhongguancun', label: '中关村' },
{ value: 'wudaokou', label: '五道口' }
]
},
{ value: 'dongcheng', label: '东城区' }
]
},
{
value: 'guangzhou',
label: '广州',
children: [
{ value: 'tianhe', label: '天河区' },
{ value: 'yuexiu', label: '越秀区' }
]
}
]
</script>
<template>
<NsCascader v-model="value" :options="options" check-strictly clearable />
</template>
多选
加上 multiple 后每个节点前面有复选框,绑定值是路径的数组,选中的项显示成标签。
- 勾选父节点等于勾选它下面所有没禁用的最后一级,绑定值里只存最后一级的路径;只勾了一部分时父节点显示半选。
- 点父节点的文字只展开下一级,点复选框才勾选。
- 点标签上的叉移除这一项。
<script setup lang="ts">
import { ref } from 'vue'
import { NsCascader } from '@ns/ui'
import type { CascaderOption } from '@ns/ui'
const value = ref<(string | number)[][]>([
['beijing', 'haidian', 'wudaokou'],
['guangzhou', 'tianhe']
])
const options: CascaderOption[] = [
{
value: 'beijing',
label: '北京',
children: [
{
value: 'haidian',
label: '海淀区',
children: [
{ value: 'zhongguancun', label: '中关村' },
{ value: 'wudaokou', label: '五道口' }
]
},
{ value: 'dongcheng', label: '东城区' }
]
},
{
value: 'guangzhou',
label: '广州',
children: [
{ value: 'tianhe', label: '天河区' },
{ value: 'yuexiu', label: '越秀区' }
]
}
]
</script>
<template>
<NsCascader v-model="value" :options="options" multiple clearable style="width: 420px" />
</template>
同时加上 check-strictly 时父子不再关联,每一级单独勾选,勾了父节点绑定值里存的就是父节点的路径。
<script setup lang="ts">
import { ref } from 'vue'
import { NsCascader } from '@ns/ui'
import type { CascaderOption } from '@ns/ui'
const value = ref<(string | number)[][]>([])
const options: CascaderOption[] = [
{
value: 'beijing',
label: '北京',
children: [
{
value: 'haidian',
label: '海淀区',
children: [
{ value: 'zhongguancun', label: '中关村' },
{ value: 'wudaokou', label: '五道口' }
]
},
{ value: 'dongcheng', label: '东城区' }
]
},
{
value: 'guangzhou',
label: '广州',
children: [
{ value: 'tianhe', label: '天河区' },
{ value: 'yuexiu', label: '越秀区' }
]
}
]
</script>
<template>
<NsCascader v-model="value" :options="options" multiple check-strictly />
</template>
折叠标签
多选时默认显示全部标签,放不下时换行。加上 collapse-tags 后只显示前 max-collapse-tags 个(默认 1 个),其余的折叠成 +N。再加上 collapse-tags-tooltip,鼠标停在 +N 上能看到被折叠的选项。
<script setup lang="ts">
import { ref } from 'vue'
import { NsCascader, NsSpace } from '@ns/ui'
import type { CascaderOption } from '@ns/ui'
const value = ref<(string | number)[][]>([
['beijing', 'haidian', 'zhongguancun'],
['beijing', 'haidian', 'wudaokou'],
['beijing', 'dongcheng'],
['guangzhou', 'tianhe']
])
const options: CascaderOption[] = [
{
value: 'beijing',
label: '北京',
children: [
{
value: 'haidian',
label: '海淀区',
children: [
{ value: 'zhongguancun', label: '中关村' },
{ value: 'wudaokou', label: '五道口' }
]
},
{ value: 'dongcheng', label: '东城区' }
]
},
{
value: 'guangzhou',
label: '广州',
children: [
{ value: 'tianhe', label: '天河区' },
{ value: 'yuexiu', label: '越秀区' }
]
}
]
</script>
<template>
<NsSpace direction="vertical" fill>
<NsCascader v-model="value" :options="options" multiple collapse-tags />
<NsCascader v-model="value" :options="options" multiple collapse-tags :max-collapse-tags="2" />
<NsCascader v-model="value" :options="options" multiple collapse-tags collapse-tags-tooltip />
</NsSpace>
</template>
可搜索
加上 filterable 后,展开时输入框可以打字。搜索结果是一个列表,每一行显示完整路径;路径上任意一级的文字包含关键词就算匹配(不区分大小写)。结果里只列出能选的节点:默认是最后一级,check-strictly 时是所有节点。多选时搜索结果前面也有复选框。
下面依次是单选、多选、check-strictly,都输入“海淀”对比结果:
<script setup lang="ts">
import { ref } from 'vue'
import { NsCascader, NsSpace } from '@ns/ui'
import type { CascaderOption } from '@ns/ui'
const value = ref<(string | number)[]>()
const values = ref<(string | number)[][]>([])
const strictValue = ref<(string | number)[]>()
const options: CascaderOption[] = [
{
value: 'beijing',
label: '北京',
children: [
{
value: 'haidian',
label: '海淀区',
children: [
{ value: 'zhongguancun', label: '中关村' },
{ value: 'wudaokou', label: '五道口' }
]
},
{ value: 'dongcheng', label: '东城区' }
]
},
{
value: 'guangzhou',
label: '广州',
children: [
{ value: 'tianhe', label: '天河区' },
{ value: 'yuexiu', label: '越秀区' }
]
}
]
</script>
<template>
<NsSpace wrap>
<NsCascader
v-model="value"
:options="options"
filterable
placeholder="单选"
style="width: 220px"
/>
<NsCascader
v-model="values"
:options="options"
filterable
multiple
placeholder="多选"
style="width: 300px"
/>
<NsCascader
v-model="strictValue"
:options="options"
filterable
check-strictly
placeholder="任意一级"
style="width: 220px"
/>
</NsSpace>
</template>
debounce 设置停止输入多少毫秒后才开始搜索,默认 300,小于等于 0 时不防抖。before-filter 在每次搜索前调用,返回 false(或者 resolve 为 false 的 Promise)时不搜索,并清空输入的内容。
左边防抖 500 毫秒,输入里带数字时不搜索;右边的 before-filter 返回 Promise,用 setTimeout 模拟 500 毫秒的接口校验,输入“测试”会被拦下:
<script setup lang="ts">
import { ref } from 'vue'
import { NsCascader, NsSpace } from '@ns/ui'
import type { CascaderOption } from '@ns/ui'
const value = ref<(string | number)[]>()
const asyncValue = ref<(string | number)[]>()
const options: CascaderOption[] = [
{
value: 'beijing',
label: '北京',
children: [
{
value: 'haidian',
label: '海淀区',
children: [
{ value: 'zhongguancun', label: '中关村' },
{ value: 'wudaokou', label: '五道口' }
]
},
{ value: 'dongcheng', label: '东城区' }
]
},
{
value: 'guangzhou',
label: '广州',
children: [
{ value: 'tianhe', label: '天河区' },
{ value: 'yuexiu', label: '越秀区' }
]
}
]
// 输入里带数字时不搜索
const beforeFilter = (query: string) => !/\d/.test(query)
// 模拟接口校验关键词
const checkKeyword = (query: string) =>
new Promise<boolean>((resolve) => {
setTimeout(() => resolve(!query.includes('测试')), 500)
})
</script>
<template>
<NsSpace wrap>
<NsCascader
v-model="value"
:options="options"
filterable
:debounce="500"
:before-filter="beforeFilter"
placeholder="带数字时不搜索"
style="width: 240px"
/>
<NsCascader
v-model="asyncValue"
:options="options"
filterable
:before-filter="checkKeyword"
placeholder="输入“测试”会被拦下"
style="width: 240px"
/>
</NsSpace>
</template>
尺寸
size 有 large、default、small 三种,和同尺寸的 NsInput、NsButton 一致:高度 40 / 32 / 24px,字号 16 / 14 / 12px,圆角 8 / 6 / 4px。下拉面板也跟着变,选项行高 40 / 约 36 / 28px,字号 16 / 14 / 12px,左右内边距 16 / 12 / 8px,选项文字和输入框里的文字左边齐平;多选时选项前面的复选框也跟着 Cascader 的尺寸(方框 18 / 16 / 14px),不跟着外面的 Form。不写 size 时依次跟随所在的 NsFormItem、NsForm、NsConfigProvider 的 size,都没有时是 default。
每一行是一种尺寸,依次是单选(可清空)、多选、同尺寸的按钮:
<script setup lang="ts">
import { ref } from 'vue'
import { NsButton, NsCascader, NsSpace } from '@ns/ui'
import type { CascaderOption } from '@ns/ui'
const value = ref<(string | number)[]>(['beijing', 'dongcheng'])
const values = ref<(string | number)[][]>([['guangzhou', 'tianhe']])
const options: CascaderOption[] = [
{
value: 'beijing',
label: '北京',
children: [
{
value: 'haidian',
label: '海淀区',
children: [
{ value: 'zhongguancun', label: '中关村' },
{ value: 'wudaokou', label: '五道口' }
]
},
{ value: 'dongcheng', label: '东城区' }
]
},
{
value: 'guangzhou',
label: '广州',
children: [
{ value: 'tianhe', label: '天河区' },
{ value: 'yuexiu', label: '越秀区' }
]
}
]
</script>
<template>
<NsSpace direction="vertical" align="start">
<NsSpace wrap>
<span class="row-label">large</span>
<NsCascader v-model="value" :options="options" size="large" clearable style="width: 200px" />
<NsCascader v-model="values" :options="options" size="large" multiple style="width: 260px" />
<NsButton size="large">按钮</NsButton>
</NsSpace>
<NsSpace wrap>
<span class="row-label">default</span>
<NsCascader v-model="value" :options="options" clearable style="width: 200px" />
<NsCascader v-model="values" :options="options" multiple style="width: 260px" />
<NsButton>按钮</NsButton>
</NsSpace>
<NsSpace wrap>
<span class="row-label">small</span>
<NsCascader v-model="value" :options="options" size="small" clearable style="width: 200px" />
<NsCascader v-model="values" :options="options" size="small" multiple style="width: 260px" />
<NsButton size="small">按钮</NsButton>
</NsSpace>
</NsSpace>
</template>
<style scoped>
.row-label {
display: inline-block;
width: 56px;
color: var(--ns-text-color-secondary);
font-size: var(--ns-font-size-sm);
}
</style>
自定义字段名
数据里的字段名不是 value、label、children、disabled 时,用 props 指定对应的字段名。
<script setup lang="ts">
import { ref } from 'vue'
import { NsCascader } from '@ns/ui'
import type { CascaderOption } from '@ns/ui'
const value = ref<(string | number)[]>()
const departments = [
{
code: 'dev',
name: '研发部',
items: [
{ code: 'fe', name: '前端组' },
{ code: 'be', name: '后端组' },
{ code: 'qa', name: '测试组(停用)', locked: true }
]
},
{ code: 'ops', name: '运维部' }
] as unknown as CascaderOption[]
const fieldNames = { value: 'code', label: 'name', children: 'items', disabled: 'locked' }
</script>
<template>
<NsCascader v-model="value" :options="departments" :props="fieldNames" style="width: 280px" />
</template>
空数据提示
options 为空,或者搜索后没有结果时,下拉层显示“暂无数据”。用 empty 插槽可以换成别的内容。左边是没有选项,右边可以搜一个不存在的词看看:
<script setup lang="ts">
import { ref } from 'vue'
import { NsCascader, NsSpace } from '@ns/ui'
import type { CascaderOption } from '@ns/ui'
const value = ref<(string | number)[]>()
const area = ref<(string | number)[]>()
const options: CascaderOption[] = [
{
value: 'guangzhou',
label: '广州',
children: [
{ value: 'tianhe', label: '天河区' },
{ value: 'yuexiu', label: '越秀区' }
]
}
]
</script>
<template>
<NsSpace wrap>
<NsCascader v-model="value" :options="[]" style="width: 240px">
<template #empty>还没有可选的内容</template>
</NsCascader>
<NsCascader
v-model="area"
:options="options"
filterable
placeholder="输入“深圳”试试"
style="width: 240px"
>
<template #empty>没有找到这个地区</template>
</NsCascader>
</NsSpace>
</template>
事件
change 只在用户操作导致值变化时触发;expand-change 在展开的路径变化时触发;visible-change 在下拉层展开、收起时触发;remove-tag 在多选移除一项时触发(点标签上的叉或取消勾选);clear 在点清除按钮时触发。最近的事件显示在下方:
<script setup lang="ts">
import { ref } from 'vue'
import { NsCascader, NsSpace } from '@ns/ui'
import type { CascaderOption } from '@ns/ui'
const values = ref<(string | number)[][]>([['beijing', 'dongcheng']])
const logs = ref<string[]>([])
const options: CascaderOption[] = [
{
value: 'beijing',
label: '北京',
children: [
{
value: 'haidian',
label: '海淀区',
children: [
{ value: 'zhongguancun', label: '中关村' },
{ value: 'wudaokou', label: '五道口' }
]
},
{ value: 'dongcheng', label: '东城区' }
]
},
{
value: 'guangzhou',
label: '广州',
children: [
{ value: 'tianhe', label: '天河区' },
{ value: 'yuexiu', label: '越秀区' }
]
}
]
const log = (text: string) => {
logs.value = [text, ...logs.value].slice(0, 6)
}
const onChange = (val: unknown) => log(`change:${JSON.stringify(val)}`)
const onExpandChange = (path: (string | number)[]) =>
log(`expand-change:${JSON.stringify(path)}`)
const onVisibleChange = (visible: boolean) => log(`visible-change:${visible}`)
const onRemoveTag = (path: (string | number)[]) => log(`remove-tag:${JSON.stringify(path)}`)
</script>
<template>
<NsSpace direction="vertical" fill>
<NsCascader
v-model="values"
:options="options"
multiple
clearable
style="max-width: 400px"
@change="onChange"
@expand-change="onExpandChange"
@visible-change="onVisibleChange"
@remove-tag="onRemoveTag"
@clear="log('clear')"
/>
<div class="logs">
<div v-if="logs.length === 0">还没有触发事件</div>
<div v-for="(item, index) in logs" :key="index">{{ item }}</div>
</div>
</NsSpace>
</template>
<style scoped>
.logs {
color: var(--ns-text-color-secondary);
font-size: var(--ns-font-size-sm);
}
</style>
调用方法
通过 ref 调用 focus()、blur()。ref 上的 selectedNodes 是当前选中项的列表,activePath 是下拉层当前展开到的路径:
<script setup lang="ts">
import { ref } from 'vue'
import { NsButton, NsCascader, NsSpace } from '@ns/ui'
import type { CascaderOption } from '@ns/ui'
const cascaderRef = ref<InstanceType<typeof NsCascader>>()
const value = ref<(string | number)[]>(['beijing', 'haidian', 'wudaokou'])
const options: CascaderOption[] = [
{
value: 'beijing',
label: '北京',
children: [
{
value: 'haidian',
label: '海淀区',
children: [
{ value: 'zhongguancun', label: '中关村' },
{ value: 'wudaokou', label: '五道口' }
]
},
{ value: 'dongcheng', label: '东城区' }
]
},
{
value: 'guangzhou',
label: '广州',
children: [
{ value: 'tianhe', label: '天河区' },
{ value: 'yuexiu', label: '越秀区' }
]
}
]
</script>
<template>
<NsSpace wrap>
<NsCascader ref="cascaderRef" v-model="value" :options="options" style="width: 260px" />
<NsButton @click="cascaderRef?.focus()">聚焦(focus)</NsButton>
<NsButton @click="cascaderRef?.blur()">失焦(blur)</NsButton>
</NsSpace>
<p style="margin-top: 12px">
selectedNodes:{{
cascaderRef?.selectedNodes.map((item) => item.pathLabels.join(' / ')).join('、')
}}<br />
activePath:{{ JSON.stringify(cascaderRef?.activePath ?? []) }}
</p>
</template>
在表单里使用
放在 NsFormItem 里时,值变化触发 change 规则,收起下拉层触发 blur 规则;不写 size、disabled 时跟随表单。下面的地区展开后不选直接收起,就会提示必填:
<script setup lang="ts">
import { reactive, ref } from 'vue'
import { NsButton, NsCascader, NsForm, NsFormItem, NsMessage, NsSpace } from '@ns/ui'
import type { CascaderOption, FormRule } from '@ns/ui'
const formRef = ref<InstanceType<typeof NsForm>>()
const model = reactive<{ area?: (string | number)[]; areas: (string | number)[][] }>({
area: undefined,
areas: []
})
const rules: Record<string, FormRule[]> = {
area: [{ required: true, message: '请选择地区', trigger: ['change', 'blur'] }],
areas: [{ required: true, message: '至少选一个服务范围', trigger: 'change' }]
}
const options: CascaderOption[] = [
{
value: 'guangzhou',
label: '广州',
children: [
{ value: 'tianhe', label: '天河区' },
{ value: 'yuexiu', label: '越秀区' }
]
},
{
value: 'shenzhen',
label: '深圳',
children: [
{ value: 'nanshan', label: '南山区' },
{ value: 'futian', label: '福田区' }
]
}
]
const submit = async () => {
const result = await formRef.value?.validate()
if (result?.valid) NsMessage.success('校验通过')
}
</script>
<template>
<NsForm ref="formRef" :model="model" :rules="rules" label-width="80px" style="max-width: 420px">
<NsFormItem label="地区" prop="area">
<NsCascader v-model="model.area" :options="options" clearable />
</NsFormItem>
<NsFormItem label="服务范围" prop="areas">
<NsCascader v-model="model.areas" :options="options" multiple clearable />
</NsFormItem>
<NsFormItem>
<NsSpace>
<NsButton type="primary" @click="submit">提交</NsButton>
<NsButton @click="formRef?.resetFields()">重置</NsButton>
</NsSpace>
</NsFormItem>
</NsForm>
</template>
键盘操作
选择器可以用 Tab 聚焦,聚焦后:
| 按键 | 作用 |
|---|---|
| Enter | 没展开时展开;展开后相当于点一下当前停留的节点(展开下一级或选中) |
| 空格 | 没展开时展开;展开后单选相当于点击,多选是勾选或取消勾选当前停留的节点 |
| ↓、↑ | 没展开时展开;展开后在同一列里移动,跳过禁用的节点,到头后循环 |
| → | 展开当前节点,停到它的第一个子节点上 |
| ← | 回到上一级 |
| Esc | 收起下拉层,焦点回到选择器 |
| Tab | 收起下拉层,焦点移到下一个元素 |
搜索时上下键在搜索结果里移动,回车选中;空格和左右键留给搜索框。
Props
| 属性 | 类型 | 默认值 | 说明 |
|---|---|---|---|
| modelValue | string | number | (string | number)[] | (string | number)[][] | - | 绑定值,支持 v-model。单选是路径数组,多选是路径数组的数组 |
| options | CascaderOption[] | - | 选项数据,必填 |
| multiple | boolean | false | 是否多选 |
| disabled | boolean | false | 是否禁用 |
| clearable | boolean | false | 有值时是否显示清除按钮 |
| filterable | boolean | false | 是否可搜索 |
| placeholder | string | '请选择' | 占位文本 |
| size | 'small' | 'default' | 'large' | 'default' | 尺寸 |
| trigger | 'click' | 'hover' | 'click' | 下一级的展开方式:点击或鼠标悬停 |
| expandTrigger | 'click' | 'hover' | - | 和 trigger 是同一个意思,两个都传时以它为准 |
| checkStrictly | boolean | false | 单选时是否可以选任意一级;多选时父子是否不关联 |
| showAllLevels | boolean | true | 输入框和标签里是否显示完整路径,false 时只显示最后一级 |
| separator | string | '/' | 路径里各级文字之间的分隔符 |
| collapseTags | boolean | false | 多选时是否折叠标签 |
| maxCollapseTags | number | 1 | 折叠前最多显示几个标签,collapseTags 为 true 时生效 |
| collapseTagsTooltip | boolean | false | 鼠标停在 +N 上时是否提示被折叠的选项 |
| debounce | number | 300 | 搜索防抖时间,单位毫秒。小于等于 0 时不防抖 |
| beforeFilter | (query: string) => boolean | Promise<boolean> | - | 搜索前调用,返回 false 时不搜索并清空输入 |
| props | CascaderFieldNames | {} | 自定义选项数据的字段名 |
| validateEvent | boolean | true | 值变化和收起下拉层时是否触发所在表单项的校验 |
Events
| 事件 | 回调参数 | 说明 |
|---|---|---|
| update:modelValue | (value: (string | number)[] | (string | number)[][] | undefined) | 值变化时触发,v-model 用 |
| change | (value: (string | number)[] | (string | number)[][] | undefined) | 用户操作导致值变化时触发(选中、勾选、移除标签、清空) |
| clear | - | 点清除按钮时触发 |
| visibleChange | (visible: boolean) | 下拉层展开或收起时触发 |
| expandChange | (path: (string | number)[]) | 展开的路径变化时触发,参数是当前展开到的路径 |
| removeTag | (path: (string | number)[]) | 多选时移除一项时触发(点标签上的叉,或者取消勾选),参数是被移除项的路径 |
Slots
| 插槽 | 作用域参数 | 说明 |
|---|---|---|
| empty | - | 没有选项或搜索没有结果时的提示,默认是“暂无数据” |
方法
通过组件的 ref 调用。
| 方法 | 参数 | 返回值 | 说明 |
|---|---|---|---|
| focus | - | void | 让选择器获得焦点;可搜索并且已展开时聚焦到搜索框 |
| blur | - | void | 让选择器失去焦点 |
ref 上还有两个只读属性:selectedNodes(当前选中项的列表,类型是 CascaderSelectedItem[])和 activePath(当前展开到的路径)。
类型
import type {
CascaderOption,
CascaderFieldNames,
CascaderNode,
CascaderSelectedItem,
CascaderSize,
CascaderTrigger
} from '@ns/ui'
interface CascaderOption {
value: string | number
label: string
children?: CascaderOption[]
disabled?: boolean
[key: string]: unknown
}
/** props 属性的结构:数据里对应的字段名 */
interface CascaderFieldNames {
value?: string
label?: string
children?: string
disabled?: string
}
/** ref 上 selectedNodes 的每一项 */
interface CascaderSelectedItem {
node: CascaderNode
/** 从第一级到这个节点的 value */
path: (string | number)[]
/** 路径上每一级的文字 */
pathLabels: string[]
}
interface CascaderNode {
value: string | number
label: string
/** 第几级,从 0 开始 */
level: number
path: (string | number)[]
pathLabels: string[]
children?: CascaderNode[]
/** 自己或者任意一级父节点被禁用 */
disabled: boolean
hasChildren: boolean
isLeaf: boolean
/** options 里对应的原始数据 */
rawOption: CascaderOption
}
type CascaderSize = 'small' | 'default' | 'large'
type CascaderTrigger = 'click' | 'hover'
注意事项
- 绑定值是路径不是单个值。单选也可以传单个
value,组件会按这个值找到节点并显示它的路径,但选择之后发出来的始终是路径数组。 - 同一级里的
value不能重复;不同父节点下可以有相同的value,因为是按完整路径区分的。 - 多选并且父子关联(没加
check-strictly)时,绑定值里只有最后一级的路径,不会出现父节点的路径。 - 绑定值里的路径在
options里找不到时不显示,输入框显示占位文字。 - 选择器默认宽度是 100%,占满父容器。需要固定宽度时用
style或class设置。 - 下拉层通过
Teleport渲染到body下,位置跟随选择器;下方或右侧放不下时会自动调整。 CascaderOption的类型要求有value和label字段。用props自定义字段名时,数据需要像上面的例子那样做类型断言。- 数据需要一次全部传入,不支持点击节点时再加载下一级。
优化点
- [x] 多选、
check-strictly多选的父节点可以勾选 - [x] 支持键盘上下左右键操作
- [ ] 支持懒加载(点击未加载的节点时再请求下一级)
- [ ] 支持自定义节点渲染
- [ ] 增加
filter-method,自定义搜索逻辑 - [ ] 增加
popper-class,自定义下拉层类名 - [ ] 增加
placement,指定下拉层弹出的位置(目前固定是bottom-start,放不下时自动调整) - [ ] 增加
focus、blur事件 - [ ]
collapse-tags-tooltip目前用的是浏览器原生的title提示,可以换成NsTooltip - [ ]
CascaderOption改成泛型,自定义字段名时不用做类型断言 - [ ] 多选时取消勾选也会触发
removeTag,可以考虑只在点标签的叉时触发