记录-vue2 自定义指令实现el-select 多选隐藏关闭按钮

4 阅读1分钟

原文地址:www.jianshu.com/p/60a97d346… 最近遇到一个需求,页面有新增和编辑两个功能,但是编辑的时候只能添加新的选项,不可删除已新增的选项。

不可删除已新增的选项,要做到两点:

  1. el-option不可操作
  2. tag不可删除
    不能选中下拉框好实现,直接给el-option设置disabled属性即可。而el-select设置multiple属性后,选中的值会放入el-tag中,但源码里el-tagdisabled没有暴露出来,可以通过给el-tag添加class,直接把删除图标隐藏掉,这样用户就没地方点删除了哈哈。

一、添加自定义指令:

**

import Vue from "vue";

Vue.directive("defaultSelect", {
  componentUpdated (el, bindings) {
    const [defaultValues] = bindings.value
    
    const dealStyle = function (tags) {
      // 因为不可删除原有值,所以原有值的index是不会变的,也就是将前n个tag的close隐藏掉即可。n即已有值的长度defaultValues.length
      tags.forEach((el, index) => {
        if (index<=defaultValues.length-1 && ![...el.classList].includes('select-tag-close-none')) {
          el.classList.add('none')
        }
      })
    }
    // 设置样式 隐藏close icon
    const tags = el.querySelectorAll('.el-tag__close')
    if (tags.length === 0) {
      // 初始化tags为空处理
      setTimeout(() => {
        const tagTemp = el.querySelectorAll('.el-tag__close')
        dealStyle(tagTemp)
      })
    } else {
      dealStyle(tags)
    }
  }
});

二、调用v-defaultSelect

**

    <el-select 
        multiple 
        v-model="form.food" 
        v-defaultSelect="[selectedFood]">
        <template>
            <el-option 
                v-for="item in foodEnum" 
                :key="item.value"  
                :disabled="selectedFood.indexOf(item.food)>-1" 
                :label="item.label" 
                :value="item.value">
            </el-option>
        </template>
    </el-select>

**

 data() {
  return {
    selectedFood: [0,1,2] // 已有值,打开编辑页面调接口时拿到
  }
  }

添加css
调用v-defaultSelect指令后,el-tag就会自动添加.none

**

.none {
  display: none !important;
}

作者:Bouc
链接:www.jianshu.com/p/378209444…
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。