el-select drop-down multi-select box el-select set the default value can not be deleted function

16445826:

Element3.0+vue3.0 el-select drop-down multi-select box el-select set default value can not be deleted function

Element-UI is a widely used Vue.js component library, among which the El-Select drop-down multi-select box component is often used in actual project development. However, in the Element 3.0 version, the default value of the El-Select drop-down multi-select box can be deleted, which may cause some unexpected situations. This article will introduce how to solve this problem and realize the function that the default value of the El-Select drop-down multi-selection box cannot be deleted.

insert image description here

Scenes

Suppose we are developing a product screening page. In the multi-selection filter conditions of product status, there is a "default" option for selecting products in the default state. We want the user to be unable to deselect the "Default" option to ensure at least one state is selected.

Functional Analysis

  • First of all, el-select does not support this function. At most, the disabled attribute of el-option can be prohibited
    . Source code:
    insert image description here

  • So we need to change the code and set the select-tag-close-none property to none when el-option disabled is true

In actual combat, just put the following code in mian.js

亿点小知识:vue3.0中是 app.directive 在 vue2.0中是 Vue
in vue3.0
insert image description here

app.directive("defaultSelect", {
    
    
  componentUpdated(el, bindings) {
    
    
    const [values, options, prop, defaultProp, defaultValue] = bindings.value;
    
    const indexs = [];
    const tempData = values.map(item => options.find(op => op[prop] === item));
    
    tempData.forEach((item, index) => {
      if (item[defaultProp] === defaultValue) {
        indexs.push(index);
      }
    });
    
    const dealStyle = function(tags) {
      tags.forEach((el, index) => {
        if (indexs.includes(index) && ![...el.classList].includes("select-tag-close-none")) {
    
    
          el.classList.add("none");
        }
      });
    };
    
    const tags = el.querySelectorAll(".el-tag__close");
    
    if (tags.length === 0) {
    
    
      setTimeout(() => {
    
    
        const tagTemp = el.querySelectorAll(".el-tag__close");
        dealStyle(tagTemp);
      });
    } else {
    
    
      dealStyle(tags);
    }
  }
});

insert image description here
The above is the el-select drop-down multi-selection box el-select set the default value and cannot be deleted. Thank you for reading.
If you encounter other problems, you can discuss and study with me in private.
If it is helpful to you, please 点赞bookmark it. Thank you~!
Pay attention to favorite bloggers and will continue to update...

Guess you like

Origin blog.csdn.net/qq2754289818/article/details/132605517