vue 区域多选和全选(全国)

147 阅读1分钟

前言

简单记录一下div编写选择多个省以及选择全选(全国)的联动效果。

效果图

chrome-capture-2022-4-27.gif

实现思路

首先准备一个selectProvinceList数组用来保存点击的省份,高亮显示就是判断这个数组是否有你点击的省份,
如果有就高亮,没有就不高亮。方法:需要用一个状态来保存全国是点击状态还是未点击状态。首先判断点击的是否是
全国然后判断selectProvinceList有没有全国。如果点击了将状态变为false,然后将所有保存的省份删除。
如果没有,则将状态改为true,合并添加provinceList。
接下来考虑不是全选以及全选状态下点击其他的省份的情况。
首先selectProvinceList有没有点击的省份,如果有就删除,没有就添加。
然后判断state.selectProvinceList.length === state.provinceList.length - 1 && !state.selectStatus
如果为真,添加全国,将状态置为true
如果为假,删除全国,状态置为false

代码记录

布局

<div class="province-content">
    <div
    :class="{'province-item':true,active:selectProvinceList.indexOf(item) > -1}"
    v-for="(item,index) in provinceList"
    :key="index"
    @click="handlerMultipleSelect(item)"
    >
      {{ item }}
    </div>
  </div>

css

.province-content {
  display: flex;
  align-content: center;
  flex-wrap: wrap;
}
.province-content .province-item {
  padding: 20px;
  margin: 5px;
  width: 15%;
  border: 1px solid #ccc;
}
.active {
  background: skyblue;
}

script

<script>
  import { toRefs,reactive } from 'vue'
  export default {
    setup() {
      const state = reactive({
        provinceList: ['全国','北京市','天津市','河北省','山西省','内蒙古自治区','辽宁省','吉林省','黑龙江省','上海市','江苏省','浙江省','安徽省','福建省','江西省','山东省','河南省','湖北省','湖南省','广东省','广西壮族自治区','海南省','重庆市','四川省','贵州省','云南省','西藏自治区','陕西省','甘肃省','青海省','宁夏回族自治区','新疆维吾尔自治区','香港','澳门','台湾'],
        selectProvinceList: [],
        selectStatus: false
      })
      const handlerMultipleSelect = (item) =>{
        if (item === '全国') {
          if (state.selectProvinceList.indexOf(item) > -1) {
            state.selectStatus = false
            state.selectProvinceList = []
          } else {
            state.selectStatus = true
            state.selectProvinceList = [...state.provinceList]
          }
        } else {
          const idx = state.selectProvinceList.indexOf(item)
          if (idx > -1) {
            state.selectProvinceList.splice(idx, 1)
          } else {
            state.selectProvinceList.push(item)
          }
          if (state.selectProvinceList.length === state.provinceList.length - 1 && !state.selectStatus) {
            state.selectStatus = true
            state.selectProvinceList.push('全国')
          } else {
            if (state.selectStatus) {
              state.selectStatus = false
              const idxAll = state.selectProvinceList.indexOf('全国')
              if (idxAll > -1) {
                state.selectProvinceList.splice(idxAll, 1)
              }
            }
          }
        }
      }
      return {
        ...toRefs(state),
        handlerMultipleSelect
      }
    }
  }
</script>