原文路径:
https://blog.csdn.net/qq_36356218/article/details/102605332
https://blog.csdn.net/lning8808/article/details/103481739
指令的代码有所改动。但核心代码源于以上两篇文章。此次记录demo,加深印象。不足之处,欢迎指正。
<template>
<el-select v-model="policy" v-disableSel="[policyMap, policy]" multiple>
<el-option
v-for="item in policyMap"
:key="item.id"
:label="item.name"
:value="item.id"
:disabled="item.disabled">
</el-option>
</el-select>
</template>
<script>
export default {
data () {
return {
policy: ['1', '2'],
policyMap: [
{
id: '1',
name: 'data1'
},
{
id: '2',
name: 'data2',
disabled: true
},
{
id: '3',
name: 'data3'
}
]
}
},
directives: {
disableSel: {
bind (el, bindings) {
const [mapData, selData] = bindings.value
const disableIndex = []
selData.forEach((selItem, index) => {
const selObj = mapData.find(mapItem => mapItem.id === selItem)
if (selObj.disabled) disableIndex.push(index)
})
setTimeout(() => { // bind时,找不到 tags,所以放个延时定时器
const tags = el.querySelectorAll('.el-tag__close')
tags.forEach((tag, index) => {
if (disableIndex.includes(index)) {
tag.classList.add('none')
}
})
})
}
}
}
}
</script>
<style>
.none {
display: none !important;
}
</style>