Cascader 级联选择器
从有层级关系的数据里逐级选择,例如省 / 市 / 区、部门 / 小组。层级不深、每级选项不多时使用;层级很深或者需要同时看到整棵树时用 HuiTreeSelect。
引入
import { HuiCascader } from '@nscode/handy-ui'
基础用法
options 传层级数据,v-model 绑定的是从第一级到选中节点的路径(每一级的 value 组成的数组)。默认只能选最后一级,选中后下拉层关闭,输入框里显示完整路径。没有选中时显示 placeholder(默认“请选择”)。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiCascader, HuiSpace } from '@nscode/handy-ui'
import type { CascaderOption } from '@nscode/handy-ui'
const value = ref<(string | number)[] | null>()
const other = ref<(string | number)[] | null>()
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'] -->
<HuiSpace direction="vertical" align="start">
<HuiSpace wrap>
<HuiCascader v-model="value" :options="options" style="width: 260px" />
<HuiCascader
v-model="other"
:options="options"
placeholder="请选择所在地区"
style="width: 260px"
/>
</HuiSpace>
<span>选中的值:{{ JSON.stringify(value) ?? 'undefined' }}</span>
</HuiSpace>
</template>
展开方式
trigger 决定怎样展开下一级:click(默认)是点击节点展开,hover 是鼠标移到节点上就展开,选中仍然需要点击。expand-trigger 和 trigger 是同一个意思,两个都传时以 expand-trigger 为准。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiCascader, HuiSpace } from '@nscode/handy-ui'
import type { CascaderOption } from '@nscode/handy-ui'
const value = ref<(string | number)[] | null>()
const hoverValue = ref<(string | number)[] | null>()
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>
<HuiSpace wrap>
<HuiCascader
v-model="value"
:options="options"
trigger="click"
placeholder="点击展开(click)"
style="width: 260px"
/>
<HuiCascader
v-model="hoverValue"
:options="options"
trigger="hover"
placeholder="悬停展开(hover)"
style="width: 260px"
/>
</HuiSpace>
</template>
只显示最后一级
show-all-levels 默认是 true,输入框和多选标签里显示完整路径。:show-all-levels="false" 时只显示选中节点自己的文字。绑定值不受影响,仍然是完整路径。上面一行是默认,下面一行是 false:
<script setup lang="ts">
import { ref } from 'vue'
import { HuiCascader, HuiSpace } from '@nscode/handy-ui'
import type { CascaderOption } from '@nscode/handy-ui'
const value = ref<(string | number)[] | null>(['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>
<HuiSpace direction="vertical" align="start">
<HuiSpace wrap>
<span class="row-label">true</span>
<HuiCascader v-model="value" :options="options" style="width: 220px" />
<HuiCascader v-model="values" :options="options" multiple style="width: 320px" />
</HuiSpace>
<HuiSpace wrap>
<span class="row-label">false</span>
<HuiCascader
v-model="value"
:options="options"
:show-all-levels="false"
style="width: 220px"
/>
<HuiCascader
v-model="values"
:options="options"
multiple
:show-all-levels="false"
style="width: 320px"
/>
</HuiSpace>
</HuiSpace>
</template>
<style scoped>
.row-label {
display: inline-block;
width: 56px;
color: var(--hui-text-color-secondary);
font-size: var(--hui-font-size-sm);
}
</style>
自定义分隔符
separator 设置路径里各级文字之间的分隔符,默认是 /,前后不带空格。输入框、多选标签和搜索结果里的路径都用它。需要空格时写在分隔符里,例如 ' / '。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiCascader, HuiSpace } from '@nscode/handy-ui'
import type { CascaderOption } from '@nscode/handy-ui'
const value = ref<(string | number)[] | null>(['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>
<HuiSpace direction="vertical" align="start">
<HuiSpace wrap>
<span class="row-label">'/'</span>
<HuiCascader v-model="value" :options="options" style="width: 260px" />
</HuiSpace>
<HuiSpace wrap>
<span class="row-label">' / '</span>
<HuiCascader v-model="value" :options="options" separator=" / " style="width: 260px" />
</HuiSpace>
<HuiSpace wrap>
<span class="row-label">' > '</span>
<HuiCascader v-model="value" :options="options" separator=" > " style="width: 260px" />
</HuiSpace>
<HuiSpace wrap>
<span class="row-label">'-'</span>
<HuiCascader v-model="value" :options="options" separator="-" style="width: 260px" />
</HuiSpace>
</HuiSpace>
</template>
<style scoped>
.row-label {
display: inline-block;
width: 56px;
color: var(--hui-text-color-secondary);
font-size: var(--hui-font-size-sm);
white-space: pre;
}
</style>
可清空
加上 clearable 后,有值时右侧显示清除按钮(没值或禁用时不显示)。点击后单选的值变成 null,多选的值变成 [],依次触发 update:modelValue、clear、change。父组件接受清空后才改变显示;null 可保留 JSON 序列化字段,路径中的 0、空字符串仍是真实节点值。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiCascader, HuiSpace } from '@nscode/handy-ui'
import type { CascaderOption } from '@nscode/handy-ui'
const value = ref<(string | number)[] | null>(['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>
<HuiSpace wrap>
<HuiCascader v-model="value" :options="options" clearable style="width: 260px" />
<HuiCascader v-model="values" :options="options" multiple clearable style="width: 320px" />
</HuiSpace>
<p style="margin-top: 12px">
单选:{{ JSON.stringify(value) ?? 'undefined' }};多选:{{ JSON.stringify(values) }}
</p>
</template>
禁用
disabled 禁用整个选择器:不能展开,有值时也不显示清除按钮,多选的标签上没有叉。选项数据里的 disabled: true 禁用这个节点:它不能选也不能展开,所以它下面的节点也都选不到;多选时勾选父节点也不会勾上它。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiCascader, HuiSpace } from '@nscode/handy-ui'
import type { CascaderOption } from '@nscode/handy-ui'
const empty = ref<(string | number)[] | null>()
const single = ref<(string | number)[] | null>(['beijing', 'haidian'])
const multi = ref<(string | number)[][]>([
['beijing', 'haidian'],
['beijing', 'dongcheng']
])
const value = ref<(string | number)[] | null>()
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>
<HuiSpace direction="vertical" align="start">
<HuiSpace wrap>
<span class="row-label">整体禁用</span>
<HuiCascader v-model="empty" :options="options" disabled style="width: 200px" />
<HuiCascader v-model="single" :options="options" disabled clearable style="width: 200px" />
<HuiCascader v-model="multi" :options="options" multiple disabled style="width: 300px" />
</HuiSpace>
<HuiSpace wrap>
<span class="row-label">选项禁用</span>
<HuiCascader v-model="value" :options="options" style="width: 200px" />
<HuiCascader v-model="values" :options="options" multiple style="width: 300px" />
</HuiSpace>
</HuiSpace>
</template>
<style scoped>
.row-label {
display: inline-block;
width: 56px;
color: var(--hui-text-color-secondary);
font-size: var(--hui-font-size-sm);
}
</style>
可选任意一级
加上 check-strictly 后每一级都可以选。点还有下一级的节点会选中它并展开下一级,下拉层不关闭;点到最后一级才关闭。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiCascader } from '@nscode/handy-ui'
import type { CascaderOption } from '@nscode/handy-ui'
const value = ref<(string | number)[] | null>()
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>
<HuiCascader v-model="value" :options="options" check-strictly clearable />
</template>
多选
加上 multiple 后每个节点前面有复选框,绑定值是路径的数组,选中的项显示成标签。
- 勾选父节点等于勾选它下面所有没禁用的最后一级,绑定值里只存最后一级的路径;只勾了一部分时父节点显示半选。
- 点父节点的文字只展开下一级,点复选框才勾选。
- 点标签上的叉移除这一项。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiCascader } from '@nscode/handy-ui'
import type { CascaderOption } from '@nscode/handy-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>
<HuiCascader v-model="value" :options="options" multiple clearable style="width: 420px" />
</template>
同时加上 check-strictly 时父子不再关联,每一级单独勾选,勾了父节点绑定值里存的就是父节点的路径。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiCascader } from '@nscode/handy-ui'
import type { CascaderOption } from '@nscode/handy-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>
<HuiCascader v-model="value" :options="options" multiple check-strictly />
</template>
折叠标签
多选时默认开启 collapse-tags,显示前 max-collapse-tags 个标签(默认 3 个),其余折叠成 +N。:collapse-tags="false" 显示全部标签;collapse-tags-tooltip 默认关闭,开启后鼠标停在 +N 上能看到被折叠的选项。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiCascader, HuiSpace } from '@nscode/handy-ui'
import type { CascaderOption } from '@nscode/handy-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>
<HuiSpace direction="vertical" fill>
<HuiCascader v-model="value" :options="options" multiple collapse-tags />
<HuiCascader v-model="value" :options="options" multiple collapse-tags :max-collapse-tags="2" />
<HuiCascader v-model="value" :options="options" multiple collapse-tags collapse-tags-tooltip />
</HuiSpace>
</template>
可搜索
加上 filterable 后,展开时输入框可以打字。搜索结果是一个列表,每一行显示完整路径;路径上任意一级的文字包含关键词就算匹配(不区分大小写)。结果里只列出能选的节点:默认是最后一级,check-strictly 时是所有节点。多选时搜索结果前面也有复选框。
下面依次是单选、多选、check-strictly,都输入“海淀”对比结果:
<script setup lang="ts">
import { ref } from 'vue'
import { HuiCascader, HuiSpace } from '@nscode/handy-ui'
import type { CascaderOption } from '@nscode/handy-ui'
const value = ref<(string | number)[] | null>()
const values = ref<(string | number)[][]>([])
const strictValue = ref<(string | number)[] | null>()
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>
<HuiSpace wrap>
<HuiCascader
v-model="value"
:options="options"
filterable
placeholder="单选"
style="width: 220px"
/>
<HuiCascader
v-model="values"
:options="options"
filterable
multiple
placeholder="多选"
style="width: 300px"
/>
<HuiCascader
v-model="strictValue"
:options="options"
filterable
check-strictly
placeholder="任意一级"
style="width: 220px"
/>
</HuiSpace>
</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 { HuiCascader, HuiSpace } from '@nscode/handy-ui'
import type { CascaderOption } from '@nscode/handy-ui'
const value = ref<(string | number)[] | null>()
const asyncValue = ref<(string | number)[] | null>()
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>
<HuiSpace wrap>
<HuiCascader
v-model="value"
:options="options"
filterable
:debounce="500"
:before-filter="beforeFilter"
placeholder="带数字时不搜索"
style="width: 240px"
/>
<HuiCascader
v-model="asyncValue"
:options="options"
filterable
:before-filter="checkKeyword"
placeholder="输入“测试”会被拦下"
style="width: 240px"
/>
</HuiSpace>
</template>
异步搜索检查与过期结果
beforeFilter 只有 false(或 resolve false)拦截,undefined 放行。当前检查抛错或 reject 时接住异常,开发环境输出诊断,并像 false 一样清空当前输入和已应用的搜索词。选择值不变。
每次输入立即使旧检查失效,不等下一次防抖开始;即使经历 A→B→A、清空、关闭重开,旧检查也不能清掉新词或提前应用结果。关闭动画结束后恢复面板的时机保持不变。取消只废弃结果,不终止业务请求,因此下面的日志仍可能记录旧检查完成。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiCascader, HuiSpace } from '@nscode/handy-ui'
import type { CascaderOption } from '@nscode/handy-ui'
const guardValue = ref<(string | number)[] | null>()
const guardOptions: CascaderOption[] = [
{ value: 'slow', label: '慢结果' },
{ value: 'fast', label: '快结果' },
{ value: 'sync', label: '同步结果' }
]
const guardMessages = ref<string[]>([])
const recordGuard = (message: string) => {
guardMessages.value = [message, ...guardMessages.value].slice(0, 8)
}
const guardBeforeFilter = (query: string): boolean | void | Promise<boolean | void> => {
recordGuard(`开始检查:${query}`)
if (query.includes('同步')) {
recordGuard(`同步放行:${query}`)
return
}
return new Promise<boolean | void>((resolve, reject) => {
setTimeout(
() => {
if (query.includes('异常')) {
recordGuard(`检查异常:${query}`)
reject(new Error('演示搜索检查异常'))
return
}
const allowed = !query.includes('拒绝')
recordGuard(`检查完成:${query},${allowed ? '放行' : '拦截'}`)
resolve(allowed ? undefined : false)
},
query.includes('慢') ? 1200 : 250
)
})
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<span>依次输入“慢”“快”:旧检查完成不会覆盖新结果;“同步”返回 undefined 放行。</span>
<span>输入“拒绝”或“异常”:仅当前检查拦截时清空搜索,选择值不变。</span>
<HuiCascader
v-model="guardValue"
:options="guardOptions"
:before-filter="guardBeforeFilter"
:debounce="200"
filterable
placeholder="输入慢、快、同步、拒绝或异常"
style="width: 360px; max-width: 100%; flex: none"
/>
<span>当前选择:{{ guardValue?.join('/') || '未选择' }}</span>
<ol>
<li v-for="(message, index) in guardMessages" :key="index">{{ message }}</li>
</ol>
</HuiSpace>
</template>
尺寸
size 有 large、default、small 三种,和同尺寸的 HuiInput、HuiButton 一致:高度 40 / 32 / 24px,字号 16 / 14 / 12px,圆角 8 / 6 / 4px。下拉面板也跟着变,选项行高 40 / 约 36 / 28px,字号 16 / 14 / 12px,左右内边距 16 / 12 / 8px,选项文字和输入框里的文字左边齐平;多选时选项前面的复选框也跟着 Cascader 的尺寸(方框 18 / 16 / 14px),不跟着外面的 Form。不写 size 时依次跟随所在的 HuiFormItem、HuiForm、HuiConfigProvider 的 size,都没有时是 default。
每一行是一种尺寸,依次是单选(可清空)、多选、同尺寸的按钮:
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiCascader, HuiSpace } from '@nscode/handy-ui'
import type { CascaderOption } from '@nscode/handy-ui'
const value = ref<(string | number)[] | null>(['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>
<HuiSpace direction="vertical" align="start">
<HuiSpace wrap>
<span class="row-label">large</span>
<HuiCascader v-model="value" :options="options" size="large" clearable style="width: 200px" />
<HuiCascader v-model="values" :options="options" size="large" multiple style="width: 260px" />
<HuiButton size="large">按钮</HuiButton>
</HuiSpace>
<HuiSpace wrap>
<span class="row-label">default</span>
<HuiCascader v-model="value" :options="options" clearable style="width: 200px" />
<HuiCascader v-model="values" :options="options" multiple style="width: 260px" />
<HuiButton>按钮</HuiButton>
</HuiSpace>
<HuiSpace wrap>
<span class="row-label">small</span>
<HuiCascader v-model="value" :options="options" size="small" clearable style="width: 200px" />
<HuiCascader v-model="values" :options="options" size="small" multiple style="width: 260px" />
<HuiButton size="small">按钮</HuiButton>
</HuiSpace>
</HuiSpace>
</template>
<style scoped>
.row-label {
display: inline-block;
width: 56px;
color: var(--hui-text-color-secondary);
font-size: var(--hui-font-size-sm);
}
</style>
自定义字段名
数据里的字段名不是 value、label、children、disabled 时,用 props 指定对应的字段名。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiCascader } from '@nscode/handy-ui'
import type { CascaderOption } from '@nscode/handy-ui'
const value = ref<(string | number)[] | null>()
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>
<HuiCascader v-model="value" :options="departments" :props="fieldNames" style="width: 280px" />
</template>
空数据提示
options 为空,或者搜索后没有结果时,下拉层显示“暂无数据”。用 empty 插槽可以换成别的内容。左边是没有选项,右边可以搜一个不存在的词看看:
<script setup lang="ts">
import { ref } from 'vue'
import { HuiCascader, HuiSpace } from '@nscode/handy-ui'
import type { CascaderOption } from '@nscode/handy-ui'
const value = ref<(string | number)[] | null>()
const area = ref<(string | number)[] | null>()
const options: CascaderOption[] = [
{
value: 'guangzhou',
label: '广州',
children: [
{ value: 'tianhe', label: '天河区' },
{ value: 'yuexiu', label: '越秀区' }
]
}
]
</script>
<template>
<HuiSpace wrap>
<HuiCascader v-model="value" :options="[]" style="width: 240px">
<template #empty>还没有可选的内容</template>
</HuiCascader>
<HuiCascader
v-model="area"
:options="options"
filterable
placeholder="输入“深圳”试试"
style="width: 240px"
>
<template #empty>没有找到这个地区</template>
</HuiCascader>
</HuiSpace>
</template>
事件
change 在用户选择、勾选、移除标签或清空时报告本次请求值,实际显示仍遵从父组件回填;expand-change 在展开的路径变化时触发;visible-change 在下拉层展开、收起时触发;remove-tag 仅在点击标签上的叉时触发,取消勾选通过 change 观察;clear 在点清除按钮或调用clear()时触发。最近的事件显示在下方:
<script setup lang="ts">
import { ref } from 'vue'
import { HuiCascader, HuiSpace } from '@nscode/handy-ui'
import type { CascaderOption } from '@nscode/handy-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>
<HuiSpace direction="vertical" fill>
<HuiCascader
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>
</HuiSpace>
</template>
<style scoped>
.logs {
color: var(--hui-text-color-secondary);
font-size: var(--hui-font-size-sm);
}
</style>
调用方法
通过 ref 调用 focus()、blur()。ref 上的 selectedNodes 是当前选中项的列表,activePath 是下拉层当前展开到的路径:
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiCascader, HuiSpace } from '@nscode/handy-ui'
import type { CascaderOption } from '@nscode/handy-ui'
const cascaderRef = ref<InstanceType<typeof HuiCascader>>()
const value = ref<(string | number)[] | null>(['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>
<HuiSpace wrap>
<HuiCascader ref="cascaderRef" v-model="value" :options="options" style="width: 260px" />
<HuiButton @click="cascaderRef?.focus()">聚焦(focus)</HuiButton>
<HuiButton @click="cascaderRef?.blur()">失焦(blur)</HuiButton>
</HuiSpace>
<p style="margin-top: 12px">
selectedNodes:{{
cascaderRef?.selectedNodes.map((item) => item.pathLabels.join(' / ')).join('、')
}}<br />
activePath:{{ JSON.stringify(cascaderRef?.activePath ?? []) }}
</p>
</template>
在表单里使用
放在 HuiFormItem 里时,值变化触发 change 规则,收起下拉层触发 blur 规则;不写 size、disabled 时跟随表单。下面的地区展开后不选直接收起,就会提示必填:
<script setup lang="ts">
import { reactive, ref } from 'vue'
import {
HuiButton,
HuiCascader,
HuiForm,
HuiFormItem,
HuiMessage,
HuiSpace
} from '@nscode/handy-ui'
import type { CascaderOption, FormRule } from '@nscode/handy-ui'
const formRef = ref<InstanceType<typeof HuiForm>>()
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) HuiMessage.success('校验通过')
}
</script>
<template>
<HuiForm ref="formRef" :model="model" :rules="rules" label-width="80px" style="max-width: 420px">
<HuiFormItem label="地区" prop="area">
<HuiCascader v-model="model.area" :options="options" clearable />
</HuiFormItem>
<HuiFormItem label="服务范围" prop="areas">
<HuiCascader v-model="model.areas" :options="options" multiple clearable />
</HuiFormItem>
<HuiFormItem>
<HuiSpace>
<HuiButton type="primary" @click="submit">提交</HuiButton>
<HuiButton @click="formRef?.resetFields()">重置</HuiButton>
</HuiSpace>
</HuiFormItem>
</HuiForm>
</template>
键盘操作
选择器可以用 Tab 聚焦,聚焦后:
| 按键 | 作用 |
|---|---|
| Enter | 没展开时展开;展开后相当于点一下当前停留的节点(展开下一级或选中) |
| 空格 | 没展开时展开;展开后单选相当于点击,多选是勾选或取消勾选当前停留的节点 |
| ↓、↑ | 没展开时展开;展开后在同一列里移动,跳过禁用的节点,到头后循环 |
| → | 展开当前节点,停到它的第一个子节点上 |
| ← | 回到上一级 |
| Home、End | 仅不可搜索(filterable=false)且已展开时,移到当前列首个、末个可用节点 |
| Esc | 收起下拉层,焦点回到选择器 |
| Tab | 收起下拉层,焦点移到下一个元素 |
搜索时上下键在搜索结果里循环移动,回车选中;Home、End、空格以及编辑文本时的左右键留给搜索框。输入法组合中的按键、键码229及带Alt、Ctrl、Meta的按键不触发导航或选择。
高亮按完整路径保存。同一查询下,父组件重绘、等值数据回填或选项重排不会把仍有效的高亮重置到首项;应用新搜索词时回到首个可用结果。当前项被删除或禁用时,优先同列原位置及后方,再找前方可用项;该列或父路径失效才逐层回退。数据更新只调整高亮,不主动移动真实焦点或发出选择事件。
自持与受控
未传modelValue或仅监听更新时,单选从null、多选从空数组保存内部状态;显式传入即受控,undefined为空。显示、标签、选中状态和表单校验使用实际值。父拒绝选择、移除或清空时保留父选择,多选连续请求也从父实际路径重新计算。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiCascader, HuiSpace } from '@nscode/handy-ui'
import type { CascaderOption, CascaderProps } from '@nscode/handy-ui'
const cascadeOptions: CascaderOption[] = [
{ value: 'a', label: '甲', children: [{ value: 'a1', label: '甲一' }] },
{ value: 'b', label: '乙' },
{ value: 'c', label: '丙' }
]
const cascadeSingle = ref<CascaderProps['modelValue']>(['a', 'a1'])
const cascadeMultiple = ref<CascaderProps['modelValue']>([['a', 'a1']])
const cascadeRedraw = ref(0)
const cascadeSingleLast = ref('暂无')
const cascadeMultipleLast = ref('暂无')
const recordCascadeSingle = (value: CascaderProps['modelValue']) => {
cascadeSingleLast.value = JSON.stringify(value) ?? 'undefined'
}
const recordCascadeMultiple = (value: CascaderProps['modelValue']) => {
cascadeMultipleLast.value = JSON.stringify(value) ?? 'undefined'
}
</script>
<template>
<HuiSpace class="cascader-q1-demo" direction="vertical" fill :data-parent="cascadeRedraw">
<HuiSpace wrap>
<HuiButton class="cascader-redraw" @click="cascadeRedraw++"
>父级重绘 {{ cascadeRedraw }}</HuiButton
>
<span>选择乙后重绘父级;固定值和显式空值保持父组件实际选择。</span>
</HuiSpace>
<HuiSpace wrap align="start">
<HuiSpace class="cascader-single" direction="vertical" style="width: 370px; max-width: 100%">
<strong>单选</strong>
<HuiSpace class="cascader-local" direction="vertical" style="width: 100%">
<span>未传模型</span>
<HuiCascader
:options="cascadeOptions"
style="width: 320px; max-width: 100%"
clearable
filterable
:debounce="0"
/>
</HuiSpace>
<HuiSpace class="cascader-listener" direction="vertical" style="width: 100%">
<span>仅监听更新</span>
<HuiCascader
@update:model-value="recordCascadeSingle"
:options="cascadeOptions"
style="width: 320px; max-width: 100%"
clearable
filterable
:debounce="0"
/>
</HuiSpace>
<HuiSpace class="cascader-empty" direction="vertical" style="width: 100%">
<span>显式 undefined</span>
<HuiCascader
:model-value="undefined"
:options="cascadeOptions"
style="width: 320px; max-width: 100%"
clearable
filterable
:debounce="0"
/>
</HuiSpace>
<HuiSpace class="cascader-fixed" direction="vertical" style="width: 100%">
<span>固定甲/甲一,父拒绝</span>
<HuiCascader
:model-value="['a', 'a1']"
:options="cascadeOptions"
style="width: 320px; max-width: 100%"
clearable
filterable
:debounce="0"
/>
</HuiSpace>
<HuiSpace class="cascader-bound" direction="vertical" style="width: 100%">
<span>双向绑定</span>
<HuiCascader
v-model="cascadeSingle"
:options="cascadeOptions"
style="width: 320px; max-width: 100%"
clearable
filterable
:debounce="0"
/>
</HuiSpace>
<span class="cascader-status"
>监听请求:{{ cascadeSingleLast }};绑定值:{{ JSON.stringify(cascadeSingle) }}</span
>
</HuiSpace>
<HuiSpace
class="cascader-multiple"
direction="vertical"
style="width: 370px; max-width: 100%"
>
<strong>多选</strong>
<HuiSpace class="cascader-local" direction="vertical" style="width: 100%">
<span>未传模型</span>
<HuiCascader
multiple
:options="cascadeOptions"
style="width: 320px; max-width: 100%"
clearable
filterable
:debounce="0"
/>
</HuiSpace>
<HuiSpace class="cascader-listener" direction="vertical" style="width: 100%">
<span>仅监听更新</span>
<HuiCascader
multiple
@update:model-value="recordCascadeMultiple"
:options="cascadeOptions"
style="width: 320px; max-width: 100%"
clearable
filterable
:debounce="0"
/>
</HuiSpace>
<HuiSpace class="cascader-empty" direction="vertical" style="width: 100%">
<span>显式 undefined</span>
<HuiCascader
multiple
:model-value="undefined"
:options="cascadeOptions"
style="width: 320px; max-width: 100%"
clearable
filterable
:debounce="0"
/>
</HuiSpace>
<HuiSpace class="cascader-fixed" direction="vertical" style="width: 100%">
<span>固定甲/甲一,父拒绝</span>
<HuiCascader
multiple
:model-value="[['a', 'a1']]"
:options="cascadeOptions"
style="width: 320px; max-width: 100%"
clearable
filterable
:debounce="0"
/>
</HuiSpace>
<HuiSpace class="cascader-bound" direction="vertical" style="width: 100%">
<span>双向绑定</span>
<HuiCascader
multiple
v-model="cascadeMultiple"
:options="cascadeOptions"
style="width: 320px; max-width: 100%"
clearable
filterable
:debounce="0"
/>
</HuiSpace>
<span class="cascader-status"
>监听请求:{{ cascadeMultipleLast }};绑定值:{{ JSON.stringify(cascadeMultiple) }}</span
>
</HuiSpace>
</HuiSpace>
</HuiSpace>
</template>
公开清空方法
通过组件ref的clear()与清除图标共用入口:单选请求null、多选请求[],顺序为update:modelValue → clear → change。clearable仅控制图标,关闭图标时方法仍可主动清空。父拒绝时保持实际路径、标签和selectedNodes;禁用、表单只读或卸载后无效。同步回调重入不重复通知,新选择或卸载会停止旧清空尾部。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiCascader, HuiSpace } from '@nscode/handy-ui'
import type { CascaderExpose, CascaderOption, CascaderProps } from '@nscode/handy-ui'
const options: CascaderOption[] = [
{ value: 0, label: '零', children: [{ value: '', label: '空串' }] },
{ value: 'b', label: '乙' }
]
const single = ref<CascaderProps['modelValue']>([0, ''])
const multiple = ref<CascaderProps['modelValue']>([[0, '']])
const singleRef = ref<CascaderExpose>()
const multipleRef = ref<CascaderExpose>()
const fixedSingleRef = ref<CascaderExpose>()
const fixedMultipleRef = ref<CascaderExpose>()
const notices = ref<Record<string, string[]>>({
single: [],
multiple: [],
fixedSingle: [],
fixedMultiple: []
})
const record = (kind: string, event: string, value?: CascaderProps['modelValue']) => {
notices.value[kind].push(value === undefined ? event : `${event}:${JSON.stringify(value)}`)
}
const reset = () => {
single.value = [0, '']
multiple.value = [[0, '']]
notices.value = { single: [], multiple: [], fixedSingle: [], fixedMultiple: [] }
}
</script>
<template>
<HuiSpace class="cascader-clear-demo" direction="vertical" fill>
<span>方法和图标共用入口:单选请求null,多选请求[];父拒绝时保持实际路径。</span>
<HuiSpace class="cascade-clear-single" wrap>
<span>单选父接受</span>
<HuiCascader
ref="singleRef"
v-model="single"
:options="options"
clearable
style="width: 240px"
@update:model-value="record('single', 'update', $event)"
@clear="record('single', 'clear')"
@change="record('single', 'change', $event)"
/>
<HuiButton class="cascade-clear-single-button" @click="singleRef?.clear()"
>单选清空</HuiButton
>
</HuiSpace>
<span class="cascade-clear-single-status"
>模型:{{ JSON.stringify(single) }};{{ notices.single.join(' → ') }}</span
>
<HuiSpace class="cascade-clear-fixed-single" wrap>
<span>单选父拒绝</span>
<HuiCascader
ref="fixedSingleRef"
:model-value="[0, '']"
:options="options"
clearable
style="width: 240px"
@update:model-value="record('fixedSingle', 'update', $event)"
@clear="record('fixedSingle', 'clear')"
@change="record('fixedSingle', 'change', $event)"
/>
<HuiButton class="cascade-clear-fixed-single-button" @click="fixedSingleRef?.clear()"
>单选请求清空</HuiButton
>
</HuiSpace>
<span class="cascade-clear-fixed-single-status">{{ notices.fixedSingle.join(' → ') }}</span>
<HuiSpace class="cascade-clear-multiple" wrap>
<span>多选父接受</span>
<HuiCascader
ref="multipleRef"
v-model="multiple"
:options="options"
multiple
clearable
style="width: 240px"
@update:model-value="record('multiple', 'update', $event)"
@clear="record('multiple', 'clear')"
@change="record('multiple', 'change', $event)"
/>
<HuiButton class="cascade-clear-multiple-button" @click="multipleRef?.clear()"
>多选清空</HuiButton
>
</HuiSpace>
<span class="cascade-clear-multiple-status"
>模型:{{ JSON.stringify(multiple) }};{{ notices.multiple.join(' → ') }}</span
>
<HuiSpace class="cascade-clear-fixed-multiple" wrap>
<span>多选父拒绝</span>
<HuiCascader
ref="fixedMultipleRef"
:model-value="[[0, '']]"
:options="options"
multiple
clearable
style="width: 240px"
@update:model-value="record('fixedMultiple', 'update', $event)"
@clear="record('fixedMultiple', 'clear')"
@change="record('fixedMultiple', 'change', $event)"
/>
<HuiButton class="cascade-clear-fixed-multiple-button" @click="fixedMultipleRef?.clear()"
>多选请求清空</HuiButton
>
</HuiSpace>
<span class="cascade-clear-fixed-multiple-status">{{ notices.fixedMultiple.join(' → ') }}</span>
<HuiButton class="cascade-clear-reset" @click="reset">恢复示例</HuiButton>
</HuiSpace>
</template>
Props
| 属性 | 类型 | 默认值 | 说明 |
|---|---|---|---|
| modelValue | string | number | (string | number)[] | (string | number)[][] | null | - | 未传或仅监听时自持;传入即受控(含undefined/null为空),支持 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' | 下一级的展开方式:点击或鼠标悬停 |
| checkStrictly | boolean | false | 单选时是否可以选任意一级;多选时父子是否不关联 |
| showAllLevels | boolean | true | 输入框和标签里是否显示完整路径,false 时只显示最后一级 |
| separator | string | '/' | 路径里各级文字之间的分隔符 |
| collapseTags | boolean | true | 多选时折叠超出的标签 |
| maxCollapseTags | number | 3 | 折叠前显示的标签数,collapseTags 为 true 时生效 |
| collapseTagsTooltip | boolean | false | 鼠标停在 +N 上时是否提示被折叠的选项 |
| debounce | number | 300 | 搜索防抖时间,单位毫秒。小于等于 0 时不防抖 |
| beforeFilter | (query: string) => boolean | void | Promise<boolean | void> | - | 搜索前调用;undefined 放行,false、throw/reject 拦截并清空当前搜索;过期结果无效 |
| props | CascaderFieldNames | {} | 自定义选项数据的字段名 |
| validateEvent | boolean | true | 值变化和收起下拉层时是否触发所在表单项的校验 |
Events
| 事件 | 回调参数 | 说明 |
|---|---|---|
| update:modelValue | (value: (string | number)[] | (string | number)[][] | null) | 值变化时触发,v-model 用 |
| change | (value: (string | number)[] | (string | number)[][] | null) | 用户选择、勾选、移除标签或清空时的请求值,父组件可接受或拒绝 |
| clear | - | 点清除按钮或调用clear()时触发 |
| visibleChange | (visible: boolean) | 下拉层展开或收起时触发 |
| expandChange | (path: (string | number)[]) | 展开的路径变化时触发,参数是当前展开到的路径 |
| removeTag | (path: (string | number)[]) | 仅点击标签上的叉时触发;取消勾选通过 change 观察 |
Slots
| 插槽 | 作用域参数 | 说明 |
|---|---|---|
| empty | - | 没有选项或搜索没有结果时的提示,默认随语言(中文:暂无数据) |
| node | { node: CascaderNode, checked: boolean } | 替换普通菜单和搜索结果的节点文字;node.rawOption 保留业务数据 |
自定义节点文字
普通菜单和搜索结果使用同一个 node 插槽。路径字段为副本;原始业务字段从 node.rawOption 读取。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiCascader, HuiSpace } from '@nscode/handy-ui'
import type { CascaderProps } from '@nscode/handy-ui'
const value = ref<CascaderProps['modelValue']>(null)
const options = [
{
value: 'a',
label: '甲区域',
count: 12,
children: [{ value: 'a1', label: '甲一', count: 6 }]
},
{ value: 'b', label: '乙区域', count: 8 }
]
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiCascader v-model="value" :options="options" filterable :debounce="0" style="width: 280px">
<template #node="{ node, checked }"
><span
>{{ node.label }}({{ node.rawOption.count }}){{ checked ? ' ✓' : '' }}</span
></template
>
</HuiCascader>
<span>路径:{{ JSON.stringify(value) }}</span>
</HuiSpace>
</template>
方法
通过组件的 ref 调用。
| 方法 | 参数 | 返回值 | 说明 |
|---|---|---|---|
| focus | - | void | 让选择器获得焦点;可搜索并且已展开时聚焦到搜索框 |
| blur | - | void | 让选择器失去焦点 |
| clear | - | void | 请求单选null或多选[];禁用、表单只读、卸载后无效,父拒绝保持实际值 |
ref 上还有两个只读属性:selectedNodes(当前选中项的列表,类型是 CascaderSelectedItem[])和 activePath(当前展开到的路径)。
类型
import type { CascaderSelectedItem } from '@nscode/handy-ui'
export interface CascaderExpose {
focus: () => void
blur: () => void
clear: () => void
readonly selectedNodes: CascaderSelectedItem[]
readonly activePath: (string | number)[]
}
import type {
CascaderOption,
CascaderFieldNames,
CascaderNode,
CascaderSelectedItem,
CascaderSize,
CascaderTrigger
} from '@nscode/handy-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
path: (string | number)[]
pathLabels: string[]
}
interface CascaderNode {
value: string | number
label: string
level: number
path: (string | number)[]
pathLabels: string[]
children?: CascaderNode[]
/** 自己或者任意一级父节点被禁用 */
disabled: boolean
hasChildren: boolean
isLeaf: boolean
rawOption: CascaderOption
}
type CascaderSize = 'small' | 'default' | 'large'
type CascaderTrigger = 'click' | 'hover'