Bootstrap

el-select多选动态控制元素能否删除及选中

需求

给定一个多选框,需要条件性控制元素能否删除,已知不能删除的元素在下拉列表中也得是禁选状态。

实现

禁选: 
	element中提供了元素的禁选状态,通过option里的disabled动态控制
	<el-select
       v-model="postData.returnCustomers"
       filterable
       multiple
       value-key="custId"
       class="input-width return-customer-tag"
     >
       <el-option
         v-for="item in returnCustomerList"
         :key="item.custId"
         :label="item.custName"
         :disabled="item.custName === '北京母公司'"
         :value="item"
       ></el-option>
     </el-select>
禁删:
	针对于历史数据,且满足一定的条件,去掉删除icon,用户即无法删除。则可以动态为满足条件的元素添加样式。

第一种直接根据jquery选择器定位到元素更改样式

this.$nextTick(() => {
  this.postData.returnCustomers.forEach((item, index) => {
     if (item.custName === '北京天下2') {
       jQuery(`.return-customer-tag .el-tag:nth-child(${index + 1}) .el-icon-close`).css('display', 'none');
     } //通过元素有序排列的特点,获取满足条件的元素索引,更改icon样式
   });
 })

第二种通过添加样式片段,需要在@change的时候同步更新元素索引对应的样式

let styleElem = window.document.head.appendChild(
                  document.createElement("style")
          );
styleElem.innerHTML = this.postData.returnCustomers
   .map(
     (item, index) =>
       `.return-customer-tag .el-tag:nth-child(${index + 1}) .el-icon-close {display: ${item.custName ==
         '北京天下2' ? 'none' : 'block'};}`
   )
   .join('');

当然是第一种比较简便,第二种看到了也觉得是个不错的思路,值得借鉴

;