el-select select all by default

el-select default select all function

I checked a lot of information and tried many times, and finally achieved the desired result.
Let's first look at the final result. Here are the problems I encountered in this project:

When the page is first opened, all are selected by default.

Let me talk about the mistakes I made before, the code:

//html部分
<template>
<el-select
   class="breakType"
   v-model="breakValueType"
   multiple
   placeholder="请选择故障类型"
   size="small"
   value-key="id"
   @change="changeBreakType"
 >
   <el-option
     v-for="item in breakOptionType"
     :key="item.id"
     :label="item.label"
     :value="item.id"
   >
   </el-option>
 </el-select>
</template>
//data部分
breakValueType: [],
breakOptionType: [
   {
    
    
     id: "1",
     label: "电流不平衡",
   },
   {
    
    
     id: "2",
     label: "控制器失控",
   },
   {
    
    
     id: "3",
     label: "灯具异常",
   },
   {
    
    
     id: "4",
     label: "过载",
   },
   {
    
    
     id: "5",
     label: "过流",
   },
   {
    
    
     id: "6",
     label: "过压",
   },
   {
    
    
     id: "7",
     label: "欠压",
   },
   {
    
    
     id: "8",
     label: "灯具漏电",
   },
   {
    
    
     id: "9",
     label: "箱变掉电",
   },
 ],
//js部分
  created() {
    
    
    this.selectAll();
  },
  methods: {
    
    
  	  selectAll() {
    
    
	      this.breakValueType = [];
	      this.breakOptionType.map((item) => {
    
    
	        this.breakValueType.push(item.label);
	     });
     },
  }

This is an error written before. After modifying it many times, I found that it is enough to change the label to id.

The following is after the change

  created() {
    
    
    this.selectAll();
  },
  methods: {
    
    
  	  selectAll() {
    
    
	      this.breakValueType = [];
	      this.breakOptionType.map((item) => {
    
    
	        this.breakValueType.push(item.id);
	     });
     },
  }

The following part is also about el-select, which is the alternate part of select all and select all found in the error, but it is not finished.

The following part is for taking notes,
//js部分
   created() {
    
    
     this.selectAll();
   },
   methods: {
    
    
    selectAll() {
    
    
      if (this.breakValueType.length < this.breakOptionType.length) {
    
    
        this.breakValueType = [];
        this.breakOptionType.map((item) => {
    
    
          this.breakValueType.push(item.id);
        });
      } else {
    
    
        this.breakValueType = [];
      }
    },
  }

Guess you like

Origin blog.csdn.net/weixin_43493113/article/details/112466974
Recommended