UseSelect.vue
<template>
<SelectAll :options="options" :propValue="propValue" : @select-hidden="getList"/>
</template>
<script lang="ts" setup>
import SelectAll from '../components/SelectAll.vue'
let propValue= ref([] as String[])
const getList =(list:string[])=>{
console.log(list);
propValue.value = list;
};
const options = [
{
value: 'Option1',
label: 'Option1',
},
{
value: 'Option2',
label: 'Option2',
},
{
value: 'Option3',
label: 'Option3',
},
{
value: 'Option4',
label: 'Option4',
},
{
value: 'Option5',
label: 'Option5',
},
]
</script>
SelectAll.vue
<template>
<el-select v-model="selectValue" class="m-2" placeholder="Select" multiple collapse-tags collapse-tags-tooltip size="large"
@change="select" @visible-change="selectHidden"
>
<el-checkbox v-model="checked1" label="全选" size="large" @change="checkAll" />
<el-option
v-for="item in options"
:key="item.value"
:label="item.label"
:value="item.value"
/>
</el-select>
</template>
<script lang="ts" setup>
import { ref } from 'vue'
interface Props {
value:string,
label:string
}
const props = defineProps<{
options: Array<Props>,
propValue:[] as String[]
}>();
const options = props.options;
let selectValue=props.propValue;
const emit = defineEmits(['select-hidden'])
const selectHidden = (e:boolean) => {
if(!e){
emit('select-hidden', selectValue.value)
}
}
const checked1=ref(false);
const checkAll = ()=>{
if(checked1.value){
options.forEach(item=>{
selectValue.value.push(item.value)
})
}else{
selectValue.value = []
}
};
const select=()=>{
if(selectValue.value.length===options.length){
checked1.value = true
}else{
checked1.value = false
}
};
</script>
再加个vue2的SelectAll.vue组件
<template>
<div>
<el-select v-model="valueList" collapse-tags multiple placeholder="请选择"
@change="select" @visible-change="selectHidden" clearable size="small">
<el-checkbox v-model="checked" label="全选" size="large" @change="checkAll" />
<el-option
v-for="item in options"
:key="item.value"
:label="item.label"
:value="item.value"
size="small">
</el-option>
</el-select>
</div>
</template>
<script>
export default {
name:'SelectAll',
props:{
options:{
default:[],
type:Array
},
value:{
default:[],
type:Array
},
},
data(){
return{
checked:false,
valueList:this.value
}
},
methods:{
selectHidden(e){
if(!e){
this.$emit("select-hidden",this.valueList)
}
},
checkAll(){
this.valueList = []
if(this.checked){
this.options.forEach(item=>{
this.valueList.push(item.value)
})
}
},
select(){
if(this.valueList.length===this.options.length){
this.checked = true
}else{
this.checked = false
}
},
}
}
</script>
<style scoped>
</style>