要求el-select支持多选,并增加全选和取消全选功能,缺点是提交的数据中会有全选这个字段
代码如下
<template>
<div>全选功能</div>
<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>
<script lang="ts" setup>
import {ref} from 'vue'
const selectedArray = ref([])
const checked = ref(false)
const options = [
{ name: '哈哈哈', label: 'one' },
{ name: '好好好', label: 'tow' },
{ name: '你好', label: 'three' },
{ name: '嘎嘎', label: 'four' },
{ name: '么么么', label: 'five' }
]
const selectAll = () => {
if (selectedArray.value.length<options.length) {
selectedArray.value = []
console.log(options)
options.map((item) => {
selectedArray.value.push(item.name)
})
selectedArray.value.unshift('全选')
} else {
selectedArray.value = []
}
}
const changeSelect = (val) => {
console.log(val)
console.log(options,'1231')
if (!val.includes('全选') && val.length === options.length) {
selectedArray.value.unshift('全选')
} else if (val.includes('全选') && (val.length - 1) < options.length) {
selectedArray.value = selectedArray.value.filter((item) => {
return item !== '全选'
})
}
}
const removeTag = (val) => {
if (val === '全选') {
selectedArray.value = []
}
}
</script>
multiple是实现下拉框多选的属性