效果图:
组件:MultipleSelect.vue
< template>
< el- select v- model= "selectValues" v- bind= "$attrs" v- on= "listeners" multiple placeholder= "请选择" style= "width: 50%" @change= "changeSelect" >
< el- option v- if = "options.length" label= "全选" value= "全选" >
< el- checkbox v- model= "isSelectAll" @click. prevent. native> 全选< / el- checkbox>
< / el- option>
< el- option v- for = "item in options" : key= "item[props.value]" : label= "item[props.label]" : value= "item[props.value]" >
< el- checkbox v- model= "item.isCheck" @click. prevent. native> { { item[ props. label] } } < / el- checkbox>
< / el- option>
< / el- select>
< / template>
< script>
export default {
name : "MultipleSelect" ,
inheritAttrs : false ,
model : {
prop : "initSelectValues" ,
event : "change"
} ,
props : {
initSelectValues : {
type : Array,
default : ( ) => [ ]
} ,
options : {
type : Array,
default : ( ) => [ ]
} ,
props : {
type : Object,
default : ( ) => {
return {
label : "label" ,
value : "value"
}
}
}
} ,
data ( ) {
return {
selectValues : [ ] ,
isSelectAll : false
}
} ,
watch : {
selectValues : {
handler ( arr ) {
this . options. forEach ( item => {
if ( arr. includes ( item[ this . props. value] ) ) {
item. isCheck = true
} else {
item. isCheck = false
}
} )
if ( arr. length === this . options. length) {
this . isSelectAll = true
} else {
this . isSelectAll = false
}
this . $forceUpdate ( )
}
}
} ,
created ( ) {
this . selectValues = this . initSelectValues
} ,
methods : {
changeSelect ( val ) {
if ( val. includes ( "全选" ) ) {
if ( val. length > this . options. length) {
this . selectValues = [ ]
} else {
this . selectValues = this . options. map ( item => item[ this . props. value] )
}
}
this . $emit ( "change" , this . selectValues)
}
}
}
< / script>
< style>
< / style>
使用:index.vue
< template>
< div id= "app" >
< MultipleSelect v- model= "value" : options= "options" > < / MultipleSelect>
< el- button @click= "confirm" > 确定< / el- button>
< / div>
< / template>
< script>
import MultipleSelect from "./components/MultipleSelect"
export default {
name : 'App' ,
components : {
MultipleSelect
} ,
data ( ) {
return {
value : [ ] ,
options : [
{
value : '选项1' ,
label : '黄金糕'
} , {
value : '选项2' ,
label : '双皮奶'
} , {
value : '选项3' ,
label : '蚵仔煎'
} , {
value : '选项4' ,
label : '龙须面'
} , {
value : '选项5' ,
label : '北京烤鸭'
}
]
}
} ,
methods : {
confirm ( ) {
console. log ( "value" , this . value)
}
}
}
< / script>
< style>
< / style>
多选框多选不换行
.el-select__tags {
flex-wrap : nowrap;
overflow : auto;
}
.el-select__tags-text {
max-width : 90px;
}