目的:多选下拉框
1.支持多选
2.支持重置和确认按钮
备注:点击确认选择的项生效,如果没有点击确认再次弹出下拉框展示的是上次确认选择的值,而不是最后离开时的选项。
先看效果图:
MultiDropdown.vue 代码如下:
<template>
<van-dropdown-item
ref="myDropDown"
:disabled="disabled"
:title="displayName || title"
@closed="closed"
>
<div style="max-height: 350px; overflow-y: scroll">
<van-checkbox-group
v-model="newValue"
direction="horizontal"
style="margin-top: 10px"
>
<van-cell v-for="(item, index) in options" :key="index">
<van-checkbox :name="item.id" shape="square"
>{{ item.text }}
</van-checkbox>
</van-cell>
</van-checkbox-group>
</div>
<div class="bottom-section">
<div class="btn-group">
<van-button
ref="regionResetBtn"
round
type="default"
size="small"
@click="reset"
class="btn-group-button"
>重置</van-button
>
<van-button
round
type="info"
size="small"
@click="confirm"
class="btn-group-button"
>确认</van-button
>
</div>
</div>
</van-dropdown-item>
</template>
<script>
export default {
name: "MultiDropdown",
model: {
prop: "value",
event: "changed",
},
props: {
title: {
type: String,
default: function () {
return "请选择";
},
},
value: {
type: Array,
default: function () {
return [];
},
},
options: {
type: Array,
default: function () {
return [];
},
},
disabled: {
type: Boolean,
default: function () {
return false;
},
},
},
data() {
return {
newValue: [], // 选中的选项ID列表
displayName: "",
isConfirm: false,
};
},
mounted() {
if (this.value.length) {
this.newValue = this.value;
this.displayName = this.getDisplyName();
}
},
methods: {
closed() {
if (!this.isConfirm) {
this.newValue = this.$utils.deepCopy(this.value);
}
this.isConfirm = false;
},
reset() {
this.newValue = [];
},
confirm() {
this.isConfirm = true;
this.displayName = this.getDisplyName();
this.$emit("changed", this.newValue);
this.$refs.myDropDown.toggle();
this.$emit("confirm");
},
getDisplyName() {
let displayName = [];
for (let keyValue of this.newValue) {
let name = this.$utils.getValueById("id", keyValue, this.options);
displayName.push(name);
}
return displayName.join(",");
},
},
watch: {
/**
* 下拉框值发生变化,重置下拉框显示的值
*/
value(newVal) {
if (!newVal.length) {
this.displayName = "";
this.newValue = this.value;
} else {
this.newValue = this.value;
this.displayName = this.getDisplyName();
}
},
/**
* 下拉框值发生变化,重置下拉框显示的值
*/
options(newVal) {
if (!newVal.length) {
this.displayName = "";
} else {
this.displayName = this.getDisplyName();
}
},
},
};
</script>
<style lang="less" scoped>
.btn-group {
justify-content: space-around;
z-index: 1;
background: @white;
}
.btn-group-button {
flex: 1;
margin-right: 20px;
}
.btn-group-button:last-child {
margin-right: 0;
}
.van-button--default {
border: 1px solid @blue;
}
</style>