如何在vue-treeselect库中实现全选功能
vue-treeselect 全选功能实现方案
vue-treeselect官方没有提供公开/未公开的全选内置配置项,不过可以通过以下两种低成本方案实现,不需要修改库源码:
方案1:在下拉列表顶部插入自定义全选节点(最常用,和你截图效果一致)
- 准备工作:在你原本的options数组最前面插入一个特殊的全选节点,示例设置id为
'select_all',label为'全选',不需要children - 提前拍平你的树结构,拿到所有可选中的叶子节点id列表存为常量,避免每次遍历树影响性能
- 监听
@select事件:当选中的节点是全选节点时,直接把v-model绑定的值赋值为「全选节点id+所有叶子节点id」的数组即可 - 监听
@deselect事件:当取消选中全选节点时,直接清空v-model绑定的数组 - 监听v-model值的变化:每次值更新时,判断排除全选id后的选中节点数量是否等于所有可选叶子节点的数量,匹配则自动把全选id加入选中数组,不匹配则自动把全选id从选中数组中移除
核心实现代码示例:
<template> <treeselect v-model="selectedValue" :options="treeOptions" :multiple="true" @select="handleSelect" @deselect="handleDeselect" /> </template> <script> import Treeselect from '@riophae/vue-treeselect' // 提前拍平得到所有可选中的叶子节点id,示例值 const ALL_LEAF_IDS = [1, 2, 3, 4, 5] export default { components: { Treeselect }, data() { return { selectedValue: [], treeOptions: [ // 开头插入全选节点 { id: 'select_all', label: '全选' }, // 下方是你原本的树配置项 { id: 1, label: '一级选项1' }, { id: 2, label: '一级选项2', children: [ { id: 3, label: '二级选项2-1' }, { id: 4, label: '二级选项2-2' } ]}, { id: 5, label: '一级选项3' } ] } }, watch: { selectedValue(newVal) { const selectedWithoutAll = newVal.filter(id => id !== 'select_all') // 已选中所有叶子节点但没选全选,自动补全选 if (selectedWithoutAll.length === ALL_LEAF_IDS.length && !newVal.includes('select_all')) { this.selectedValue.push('select_all') } // 没选全所有叶子节点但选了全选,自动移除全选 if (selectedWithoutAll.length < ALL_LEAF_IDS.length && newVal.includes('select_all')) { this.selectedValue = selectedWithoutAll } } }, methods: { handleSelect(node) { if (node.id === 'select_all') { this.selectedValue = ['select_all', ...ALL_LEAF_IDS] } }, handleDeselect(node) { if (node.id === 'select_all') { this.selectedValue = [] } } } } </script>
方案2:组件外部加全选复选框(实现成本更低)
如果不需要把全选按钮放到下拉列表内部,直接在treeselect组件旁加一个自定义的全选复选框,点击时直接给v-model赋值/清空即可,逻辑更简单,不需要监听组件内部事件。
内容的提问来源于stack exchange,提问作者Akshay Lokur
相关产品推荐
相关产品推荐

