比较简洁的方式
<el-select v-model="values" multiple placeholder="请选择"> <li class="el-select-dropdown__item" :class="{ selected: allSelected }" @click="selectAll" > <span>全选</span> </li> <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"> </el-option> </el-select>
export default { data() { return { options: [ { value: "1", label: "黄金糕" }, { value: "2", label: "双皮奶" }, { value: "3", label: "蚵仔煎" }, { value: "4", label: "龙须面" }, { value: "5", label: "北京烤鸭" } ], values: ["1", "3"], }; }, computed: { allSelected() { return this.options.length === this.values.length } }, methods: { selectAll() { this.values = !this.allSelected ? this.options.map(e => e.value) : [] } } }
Element-UI的Select组件结合CheckBox实现全选
点击 checkbox 选中状态变化,分两种情况
1、点击 checkbox 勾选上,表示全选,选中全部select选项(checked值为true,设置indeterminate值为false)
2、点击 checkbox 取消勾选,表示取消所有选择,无select选项选中(checked值为false,设置indeterminate值为false)
点击 select选项 选中状态变化,分三种情况
1、select选项 全选上,表示全选,勾选上checkbox(设置checked值为true,设置indeterminate值为false)
2、select选项 选上部分,表示部分选上,不勾选checkbox,设置checkbox样式状态为不确定状态(设置checked值为false,设置indeterminate值为true)
3、select选项 全不选,表示一个都不选择,勾掉checkbox(设置checked值为false,设置indeterminate值为false)
<template> <el-select v-model="value" multiple placeholder="请选择" @change="selectChange" > <el-checkbox v-model="checked" :indeterminate="indeterminate" @change="selectAll" class="select-checkbox" >全选</el-checkbox> <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" > </el-option> </el-select> </template> <script> export default { data() { return { value: [], checked: false, // el-checkbox 是否勾选上 indeterminate: false, // el-checkbox 的 indeterminate 属性为true时用以表示 checkbox 的不确定状态 options: [ { value: "1", label: "苹果" }, { value: "2", label: "橘子" }, { value: "3", label: "葡萄" }, { value: "4", label: "西瓜" }, { value: "5", label: "芒果" }, { value: "6", label: "山竹" }, ], }; }, methods: { // checkbox勾选操作 selectAll() { this.indeterminate = false; let selectedData = []; // 若勾选了全选,则选上所有数据 if (this.checked) { this.options.forEach((item) => { selectedData.push(item.value); }); } this.value = selectedData; }, // select下拉框选中数据变化 selectChange(val) { // 全选 if (val.length === this.options.length) { this.checked = true; this.indeterminate = false; } else if (val.length < this.options.length && val.length > 0) { // 部分选择 this.checked = false; this.indeterminate = true; } else { // 未选择 this.checked = false; this.indeterminate = false; } }, }, }; </script> <style scoped> .select-checkbox { box-sizing: border-box; width: 100%; padding: 0 0 6px 20px; border-bottom: 1px solid #eee; } </style>