<span>国家</span>
<el-divider direction="vertical"></el-divider>
<el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange" class="ml-2 mb-5">全选</el-checkbox>
<el-button v-if="shouldShowToggle" type="text" @click="toggleShowAll" style="margin-left: 20px;">
{{ showAll ? '收起' : '展开' }}
</el-button>
<el-checkbox-group v-model="checkedCities" @change="handleCheckedCitiesChange">
<div :class="showAll ? '' : 'country-list'" class="grid-container">
<el-checkbox v-for="(city, index) in displayedCities" :label="city.country_code" :key="city.country_code" class="grid-item">{{ city.country_name }}({{ city.country_code }})</el-checkbox>
</div>
</el-checkbox-group>
//script部分导入国家.json数据
import countries from './countries.json'; //存储国家数据
//data部分
data() {
return {
checkAll: false,
checkedCities: ['CN', 'US', 'JP', 'EP', 'KR'],
cities: countries,
isIndeterminate: true,
maxVisibleItems: 3, // 最多显示的项数
showAll: false,// 是否显示所有选项
}
}
//计算属性
computed: {
shouldShowToggle() {
return this.cities.length > this.maxVisibleItems;
},
displayedCities() {
if (this.showAll) {
return this.cities;
} else {
return this.cities.slice(0, this.maxVisibleItems);
}
},
}
/* methods 函数部分 */
// 切换是否显示展开所有
toggleShowAll() {
this.showAll = !this.showAll;
},
// 全选
handleCheckAllChange(val) {
if (val) {
this.checkedCities = this.cities.map(city => city.country_code);
} else {
this.checkedCities = [];
}
this.isIndeterminate = false;
},
// 单选选择城市
handleCheckedCitiesChange(val) {
let checkedCount = val.length;
this.checkAll = checkedCount === this.cities.length;
this.isIndeterminate = checkedCount > 0 && checkedCount < this.cities.length;
}
/* CSS 部分 */
.grid-container {
display: grid;
grid-template-columns: repeat(3, 1fr);
/* 每行展示3列 */
grid-gap: 10px;
/* 列之间的间距 */
}
.grid-item {
display: flex;
align-items: center;
}
//countries.json
[
{
"country_code": "EP",
"country_name": "欧洲"
},
{
"country_code": "CN",
"country_name": "中国"
},
{
"country_code": "US",
"country_name": "美国"
},
{
"country_code": "JP",
"country_name": "日本"
},
{
"country_code": "KR",
"country_name": "韩国"
},
等等等.........
]