- 需求
- <el-select>多选时,需要设置默认值,且默认值不可删除,但手动勾选的值可以删除。
- 实现原理
- 在el-select框中隐藏默认值的el-tag后面的叉
- 在option中置灰默认值的选项使其不可被操作
- 代码实现
- 新建一个自定义指令,并在<el-select>中使用
<el-select v-model="value" v-default-select="disabledIds" multiple><el-option v-for="item in options" :disabled="disabledIds.includes(item.dictType)" :label="item.dictName" :value="item.dictType":key="item.dictType"></el-option>
</el-select><script>
export default {data() {return {value: ['1','2'],disabledIds: ['1','2'],options: [{ dictType: '1', dictName: '张三' },{ dictType: '2', dictName: '李四' },{ dictType: '3', dictName: '王五' },{ dictType: '4', dictName: '赵六' },],};},directives: {defaultSelect: {inserted: function (el, bindings) {const defaultValues = bindings.valueconst dealStyle = function (tags) {tags.forEach((el, index) => {if (index <= defaultValues.length - 1 &&![...el.classList].includes('select-tag-close-none')) {el.style.display = '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)}}},},
};
</script>
- 效果