elementUI el-select 多选情况下包含全部选项,

2019-06-14  本文已影响0人  双耳云

1.在html中

<el-form-item label="用户群体" prop="cardDetail.fitUserType" label-width="120px">
  <el-select v-model="ruleForm.cardDetail.fitUserType" multiple placeholder="用户群体" @change="changeSelect">
    <el-option
      v-for="iteminfitUserType"
      :key="item.label"
      :label="item.label"
      :value="item.value"
      :disabled="item.disabled">
    </el-option>
  </el-select>
</el-form-item>

2.在script中

<script>
  export default {
    data() {
      return {
        isContainAll: true,
        ruleForm:{
          cardDetail: {
            fitUserType: ''
          },
        },
        fitUserType:[
          {value: '0',label: '所有用户',},
          {value: '1',label: '新注册用户',},
          {value: '2',label: '周活用户',},
          {value: '3',label: '付费用户',}
        ],
      }
    },
    methods: {
        changeSelect(){
        // 定义一个变量,用来存储当前下拉框是否选中了所有用户
        if (this.isContainAll) {
          // 只有下拉框的值发生了变化才会进入此方法
          // 如果之前选中了全部,则变化后肯定不包含全部了
          this.isContainAll = false;
          // 则删除第一个全部
          this.ruleForm.cardDetail.fitUserType.splice(0, 1);
        } else {
          // 如果之前没有选中全部
          // 判断此次是否选中了全部
          this.isContainAll = this.ruleForm.cardDetail.fitUserType.some(value => value === -1);
          // 如果此次选中了全部
          if (this.isContainAll) {
            // 则去除其他,只保留全部,默认value='0' 是全部
            this.ruleForm.cardDetail.fitUserType = ['0'];
          } else {
            // 如果当前不包含全部,则判断是否其他的用户是否全选了
            if (this.ruleForm.cardDetail.fitUserType.length === this.fitUserType.length - 1) {
              // 如果其他用户全选了,则也将当前置为全部
              this.ruleForm.cardDetail.fitUserType = ['0'];
              this.isContainAll = true
            }
          }
        }
        // 当没有选中任何用户时,将当前置为全部
        if (this.ruleForm.cardDetail.fitUserType.length === 0) {
          this.ruleForm.cardDetail.fitUserType = ['0'];
          this.isContainAll = true
        }
        // 如果选择全部
        if (this.isContainAll === true) {
          this.ruleForm.cardDetail.fitUserType = ['0']
        } else {
          // 获得选中的用户
          for (let i = 0; i < this.ruleForm.cardDetail.fitUserType.length; i++) {
            let obj = this.fitUserType.find((item) => {
              return item.value === this.ruleForm.cardDetail.fitUserType[i]
            });
            this.$set(this.label, i, obj.label)
          }
        }
      },
    }
  }
</script>
上一篇 下一篇

猜你喜欢

热点阅读