vue-treeselect实现多选
vue-treeselect 多选实现方法
安装 vue-treeselect 包
npm install @riophae/vue-treeselect
引入并注册组件
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
export default {
components: { Treeselect },
// ...
}
基础多选配置
data() {
return {
value: [], // 多选值必须是数组
options: [
{
id: 'group1',
label: 'Group 1',
children: [
{ id: 'item1', label: 'Item 1' },
{ id: 'item2', label: 'Item 2' }
]
}
]
}
}
模板中使用
<treeselect
v-model="value"
:multiple="true"
:options="options"
placeholder="Select items..."
/>
高级多选功能
限制选择数量
props: {
limit: 3, // 最多选择3项
limitText: count => `已选 ${count} / 3`
}
扁平化显示选项
props: {
flattenSearchResults: true
}
禁用选项
options: [
{
id: 'item1',
label: 'Item 1',
isDisabled: true // 禁用此项
}
]
样式自定义
修改默认样式
.vue-treeselect__control {
border-radius: 5px;
}
.vue-treeselect__multi-value-item {
background-color: #409eff;
}
注意事项
多选时必须将 v-model 初始化为数组
value: [] // 正确
value: null // 错误,会导致单选模式
异步加载选项时处理多选
async loadOptions({ action, parentNode, callback }) {
if (action === 'LOAD_CHILDREN_OPTIONS') {
const res = await api.getChildren(parentNode.id)
callback(null, res.data)
}
}
多选值变化监听
watch: {
value(newVal) {
console.log('Selected values:', newVal)
}
}






