在写一个功能时发现el-select支持多选,但是竟然不支持全选,好无语哦,那就自己实现一下吧~有两种方法,第二种感觉简单些
方法一:下拉项增加一个【全选】,然后应该有以下几种情况:
- 下拉选项全都勾选时,【全选】自动勾选;
- 下拉选项部分勾选时,点击【全选】后,所有下拉项全部勾选;
- 下拉选项全都未勾选时,点击【全选】后,所有下拉选项不勾选;
- 下拉选项和【全选】都选上的时候,不勾选任意下拉选项,【全选】按钮就不勾选了;
上面就是我要实现的功能,我好啰嗦。。。还是看代码吧。。。
html部分:
<template> <el-select multiple collapse-tags v-model='selectedArray' @change='changeSelect' @remove-tag='removeTag' placeholder='请选择'> <el-option label='全选' value='全选' @click.native='selectAll'></el-option> <el-option v-for='(item, index) in options' :key='index' :label='item.name' :value='item.name'></el-option> </el-select> </template>
js部分:
export default { data() { return { selectedArray: [], options: [ { name: '一一', label: 'one' }, { name: '二二', label: 'tow' }, { name: '三三', label: 'three' }, { name: '四四', label: 'four' }, { name: '五五', label: 'five' } ] } }, methods: { selectAll() { if (this.selectedArray.length < this.options.length) { this.selectedArray = [] this.options.map((item) => { this.selectedArray.push(item.name) }) this.selectedArray.unshift('全选') } else { this.selectedArray = [] } }, changeSelect(val) { if (!val.includes('全选') && val.length === this.options.length) { this.selectedArray.unshift('全选') } else if (val.includes('全选') && (val.length - 1) < this.options.length) { this.selectedArray = this.selectedArray.filter((item) => { return item !== '全选' }) } }, removeTag(val) { if (val === '全选') { this.selectedArray = [] } } } }
看看效果图:
方法二:直接添加一个【全选】复选框,实现的功能跟方法一是一样的
html部分:
<template> <el-select multiple collapse-tags v-model='selectedArray' @change='changeSelect' placeholder='请选择'> <el-checkbox v-model="checked" @change='selectAll'>全选</el-checkbox> <el-option v-for='(item, index) in options' :key='index' :label='item.name' :value='item.name'></el-option> </el-select> </template>
js部分:
export default { data() { return { checked: false, selectedArray: [], options: [ { name: '一一', label: 'one' }, { name: '二二', label: 'tow' }, { name: '三三', label: 'three' }, { name: '四四', label: 'four' }, { name: '五五', label: 'five' } ] } }, methods: { selectAll() { this.selectedArray = [] if (this.checked) { this.options.map((item) => { this.selectedArray.push(item.name) }) } else { this.selectedArray = [] } }, changeSelect(val) { if (val.length === this.options.length) { this.checked = true } else { this.checked = false } } } }
css:
.el-checkbox { text-align: right; width: 100%; padding-right: 10px; }
效果图:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。