比較簡潔的方式
<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>