最近有一个el-option增加全选的需求,后面网上找到了关于vue2的写法,这里我用的是vue3的写法。首先,先上一下效果图
选中和未选中效果图已经上传,现在贴上代码。
<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-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>
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 = []
}
}