参考文章vue+el-select下拉实现:全选、反选、清空功能
如图,优化代码,支持若依字典
import multipleSelect from '@/components/MultipleSelect/index.vue'
components: { multipleSelect },
<el-row>
<el-form-item label="分管领域" prop="manageDomainArray">
<multipleSelect v-model="form.manageDomainArray" dictName="tzLyUserDomain"></multipleSelect>
</el-form-item>
</el-row>
<template>
<div>
<el-select style="width: 100% "
v-model="selectData"
size="small"
multiple
filterable
:filter-method="selectDataFilter"
placeholder="请选择"
@change="sendMsg()">
<div class="select_up">
<el-button type="text" v-on:click="selectAll">
<i class="el-icon-circle-check"/>
全选
</el-button>
<el-button type="text" v-on:click="selectRemove">
<i class="el-icon-close"/>
清空
</el-button>
<el-button type="text" v-on:click="selectReverse">
<i class="el-icon-copy-document"/>
反选
</el-button>
</div>
<div class="select_list">
<el-option
v-for="dict in options"
:key="dict.dictValue"
:label="dict.dictLabel"
:value="dict.dictValue">
</el-option>
</div>
</el-select>
</div>
</template>
<script>
export default {
props: {
//接受父组件v-model数据
value: {
type: Array,
required: [],
default: function() {
return []
}
},
dictName: {
type: String
}
},
watch: {
//监听父组件v-model数据变化,修改子组件selectData
value(newValue, oldValue) {
this.selectData = newValue
},
// 监听子组件selectData变化,修改父组件v-model
selectData: function(newVal, oldVal) {
this.sendMsg()
}
},
data() {
return {
options: [],//下拉选项
selectData: []//选中数据
}
},
created() {
this.getDicts(this.dictName).then(res => {
this.options = res.data
// 第一次打开,初始化 selectData
this.selectData = this.value
})
},
methods: {
//清空操作
selectRemove() {
this.selectData = []
},
//全选操作
selectAll() {
this.options.map(dict => {
if (!this.selectData.includes(dict.dictValue)) {
this.selectData.push(dict.dictValue)
}
})
},
//反选操作
selectReverse() {
const val = []
this.options.forEach(dict => {
const index = this.selectData.indexOf(dict.dictValue)
if (index !== -1) {
// 已选中的项,不加入反选列表
} else {
val.push(dict.dictValue)
}
})
this.selectData = val // 直接修改 selectData 数组
},
//查询操作
selectDataFilter(query) {
if (query !== null && query !== undefined && query.trim() !== '') {
this.options.forEach(dict => {
//模糊查询并且不存在
if (dict.dictLabel.includes(query) && !this.selectData.includes(dict.dictValue)) {
this.selectData.push(dict.dictValue)
}
})
}
},
sendMsg() {
//input是默认双向绑定事件,select控件也可以用input给父组件传递数据
this.$emit('input', this.selectData)
}
}
}
</script>
<style scoped lang="scss">
.el-select-dropdown__list {
height: 100%;
overflow: hidden;
}
.select_up {
padding: 0 14px;
font-size: 14px;
position: absolute;
z-index: 99999;
background-color: white;
top: 0px;
width: 100%;
border-radius: 5px 5px 0 0;
::v-deep .el-button {
color: #bcbcbc;
font-size: 14px;
i {
font-size: 14px;
}
}
::v-deep .el-button:hover {
color: #409EFF;
}
.el-button + .el-button {
margin-left: 6px;
}
}
.select_list {
margin-top: 25px;
}
</style>