封装一个基于Vue3 + Element Plus选择框的多选下拉框有全选/全不选功能的组件,以下是示例代码和正确使用方法:
<template>
<div>
<el-select v-model="selected" multiple placeholder="请选择" @change="handleChange" collapse-tags
collapse-tags-tooltip>
<el-checkbox class="ml-15" v-model="isAllSelected" @change="handleAllChange">全选/全不选</el-checkbox>
<el-option v-for="option in options" :key="option.value" :label="option.label" :value="option.value"></el-option>
</el-select>
</div>
</template>
<script>
import { ref, watchEffect } from 'vue'
export default {
props: {
options: {
type: Array,
required: true
}
},
emits: ['update:modelValue'],
setup(props, { emit }) {
const selected = ref([])
const isAllSelected = ref(false)
// 监听选中值变化,如果全部选中则勾选全选框
watchEffect(() => {
if (selected.value.length === props.options.length) {
isAllSelected.value = true
} else {
isAllSelected.value = false
}
})
// 处理选中值变化事件
function handleChange(value) {
selected.value = value
emit('update:modelValue', selected.value)
}
// 处理全选/全不选事件
function handleAllChange(value) {
if (value) {
selected.value = props.options.map(item => item.value)
} else {
selected.value = []
}
emit('update:modelValue', selected.value)
}
return {
selected,
isAllSelected,
handleChange,
handleAllChange
}
}
}
</script>
在父组件中,正确使用这个多选下拉框有全选/全不选功能的组件,需要先导入该组件,并注册为局部组件,然后在模板中使用。同时,需要给该组件传递一个options属性,该属性是一个数组,包含了选项的数据,每个选项需要包含value和label两个属性。还需要使用v-model指令将选中值绑定到父组件的数据上,以便在父组件中获取选中值。
示例代码如下:
<template>
<div>
<my-multi-select :options="options" v-model="selected"></my-multi-select>
<p>选中的值:{{ selected }}</p>
</div>
</template>
<script>
import MyMultiSelect from './MyMultiSelect.vue'
import { ref } from 'vue'
export default {
components: {
MyMultiSelect
},
data() {
return {
options: [
{ value: 'option1', label: '选项1' },
{ value: 'option2', label: '选项2' },
{ value: 'option3', label: '选项3' }
],
selected: []
}
}
}
</script>```