Showing posts with label ELEMENT VUE. Show all posts
Showing posts with label ELEMENT VUE. Show all posts

Friday, 28 February 2020

vue js, vue element, how to add select all

<template>
 <div>
   <el-select v-model="chooseData" multiple placeholder="select" style="width: 300px" @change='selectAll'>
     <el-option v-for="item in selectOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
     </el-option>
   </el-select>
 </div>
</template>
<script>
export default {
  data () {
    return {
      selectOptions: [
        { value: 'ALL_SELECT', label: 'select all' },
        { value: '1', label: 'apple' },
        { value: '2', label: 'banana' },
        { value: '3', label: 'orange' },
        { value: '4', label: 'mango' },
        { value: '5', label: 'grape' },
      ],
      oldChooseData: [],
      chooseData: []
    };
  },
  methods: {
    selectAll (val) {
     // Get all possible values
      const allValues = this.selectOptions.map(item => {
        return item.value;
      });
      // Get previously selected values
      const oldVal = this.oldChooseData.length > 0 ? this.oldChooseData : [];

      // if  ALL_SELECT is selected this tim
      if (val.includes('ALL_SELECT')) {
        this.chooseData = allValues;
      }

      //  if  ALL_SELECT selected last time, but not this time => set selected data to []
      if (oldVal.includes('ALL_SELECT') && !val.includes('ALL_SELECT')) {
        this.chooseData = [];
      }


    // If  ALL_SELECT selected last time, and  this time as well, and there is a change in value this time meaning, some previously selected no ALL_SELECT value has been de selected,
then remove ALL_SELECT from list
      if (oldVal.includes('ALL_SELECT') && val.includes('ALL_SELECT')) {
        const index = val.indexOf('ALL_SELECT');
        val.splice(index, 1);
        this.chooseData = val;
      }

      // if ALL_SELECT not selected last time and this time as well,
      // if every other values are selected, add ALL_SELECT to selected data
      if (!oldVal.includes('ALL_SELECT') && !val.includes('ALL_SELECT')) {
        if (val.length === allValues.length - 1) {
          this.chooseData = ['ALL_SELECT'].concat(val);
        }
      }

      //  Save currently selected data for comparison next time
      this.oldChooseData = this.chooseData;
    }
  }
};
</script>
————————————————
:https://blog.csdn.net/sleepwalker_1992/article/details/88876114