遇到一个需求,选择下拉框选取图标,填充到框里
1、效果展示
2、代码
<el-form-item label="工种图标" class="Form_icon Form_label">
<el-select ref="select" :value="formLabelAlign.icon" placeholder="请选择"
:popper-append-to-body="false" @change="changIcon">
<el-option v-for="item in icons" :key="item.value" :value="item.value">
<div class="Form_label_select">
<img :src="item.icon" class="Form_label_img">
</div>
</el-option>
</el-select>
</el-form-item>
先在mounted给改下拉框添加一个
mounted() {
const newLi = document.createElement("img");
this.$refs['select'].$el.children[0].appendChild(newLi);
},
选取图标的时候更改img样式
changIcon(val) {
let item = this.icons.filter((item) => { return item.value == val })
let img = this.$refs['select'].$el.children[0].children[2];//该select数下来第三个子节点
img.setAttribute('src', item[0].icon)
img.setAttribute('style', `
width: 35px;
height:95%;
position:absolute;
left:0;
background:white;
`)
this.formLabelAlign.icon = val
},
注意:图片路径的引入得用import,否则找不到,无法显示
import icon1 from '@/assets/aaa/icon1.png';
import icon2 from '@/assets/aaa/icon2.png';
import icon3 from '@/assets/aaa/icon3.png';
icons: [{ value: '1', icon: icon1, checked: false }, { value: '2', icon: icon2, checked: false }, { value: '3', icon: icon3, checked: false },
]
::v-deep .Form_icon.el-select {
display: inline-block;
position: relative;
width: 100%;
border: 1px solid #DCDFE6;
border-radius: 4px;
padding: 2px 0 2px 12px;
box-sizing: border-box;
}
::v-deep .Form_icon.el-popper[x-placement^=bottom] {
margin-left: -10px;
}
::v-deep .Form_icon.el-input__inner {
border: none;
padding-left: 0;
}