解决element-ui里的下拉多选框 el-select 时,默认值不可删除问题

这是一个项目中常见的需求,el-select 为下拉多选,默认值不可删除,或者指定值不可删除。

实现效果:

解决思路(从el-select 的角度来考虑,其他组件组合的情况暂不考虑)

想要实现某些选项是不删除,1、需要tag 不可删除,2、options 不可选择

options 不可选择很好实现,只需要给一个disabled属性。tag 不可删除才是关键。下面是我几种解决思路。

1、 watch 进行监听,当操作不可删除的选项时,el-select 绑定的值中 将之前删除的选项重新添加到原来的位置。达到不可删除的效果。(这种方法虽然可以实现,但是tag上还是会有 “x” 会给用户一种误导)

2、使用样式,定位到 tag中,将icon “x” 设置 display:none; 将关闭 按钮隐藏,达到不可删除的效果。

3、复制一份 element-ui 中 el-select 源码 进行少量的修改,给 tag 添加一个 closagle 的属性。达到可控的效果。(这种方式增加了开发维护成本,当项目中 element-ui 升级版本的时候,需要重新对源码赋值一份进行修改)

4、使用 derictive 给 element-ui 中 tag 添加样式,实际上是对思路二的一种实现。

思路是这么一个思路,也对思路1和4进行了实现。但是综合考虑下,还是针对思路4做下记录,感觉有一点点复用意义。其它的参考价值不大。代码如下定义了一个全局的指令,也可以定义在组件里面。

 
// index.vue
 
 <el-select v-model="ruleForm.ability" multiple placeholder="请选择">
	<el-option
	 v-for="(item, index) in abilityOptions"
	 :key="index"
	 :label="`${item.abilityNameZh}(${item.abilityId})`"
	 :disabled="item.required === 1"
	 :value="item.abilityId">
	</el-option>
 </el-select>
// main.js
 
Vue.directive('defaultSelect', {
 componentUpdated (el, bindings, vnode) {
  // values v-model 绑定值
  // options 下拉选项
  // prop 对应 options 中 的 value 属性
  // defaultProp 默认值判断属性 
  // defaultValue 默认值判断值
  const [values, options, prop, defaultProp, defaultValue] = bindings.value
  // 需要隐藏的标签索引
  const indexs = []
  const tempData = values.map(a => options.find(op => op[prop] === a))
  tempData.forEach((a, index) => {
   if (a[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')
    }
   })
  }
  // 设置样式 隐藏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)
  }
 }
})
// style.css 
.none { display: none; }

补充知识:vue+elementUI+select 选中多个值,我要删除其中的一两个 方法如下

我就废话不多说了,大家还是直接看代码吧~

<el-select value-key="moduleCode"
      multiple filterable
      allow-create default-first-option
      @remove-tag='removeTag'
      v-model="ruleForm.module3" placeholder="请选择权限分类" style="width: 240px">
 <el-option v-for="item in level3" :value="item" :label="item.moduleName" :key="item.moduleCode"></el-option>
</el-select>
methods:{

removeTag(key){
 console.log(key);//获取option中item
}
}

以上这篇解决element-ui里的下拉多选框 el-select 时,默认值不可删除问题就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持来客网。