问题描述
我的代码如下:
var Main = {
data() {
return {
selectedState: null,processstates: [
{
value: 0,label: 'New',color: 'ffffff'
},{
value: 1,label: 'Ready',color: 'ff9933'
},{
value: 2,label: 'Running',color: '008000'
},{
value: 3,label: 'Rejected',color: 'cc0000'
},{
value: 4,label: 'Terminated',color: '2E9AFE'
}
]
}
},methods: {}
}
var Ctor = Vue.extend(Main);
new Ctor().$mount('#app');
@import url("//unpkg.com/element-ui@2.4.4/lib/theme-chalk/index.css");
<script src="//unpkg.com/vue/dist/vue.js"></script>
<script src="//unpkg.com/element-ui@2.4.11/lib/index.js"></script>
<div id="app">
<el-select v-model="selectedState" style="width:200px">
<el-option
v-for="state in processstates"
:key="state.value"
:label="state.label"
:value="state.value"
>
<span>
<el-tag :style="'background-color:#' + state.color"> </el-tag> {{ state.label }}
</span>
</el-option>
</el-select>
</div>
如您所见,我设法将 html 注入选项标签并获得了所需的结果。
但是,我希望在选择一个选项时具有相同的 html。
知道如何实现吗?
解决方法
您必须为此使用 prefix
槽。如下所示,我也将 selectedState 更改为对象,但您仍然可以使用 string
值,但是您必须进行查找才能获取颜色
var Main = {
data() {
return {
selectedState: { color: 'ffffff'},processStates: [
{
value: 0,label: 'New',color: 'ffffff'
},{
value: 1,label: 'Ready',color: 'ff9933'
},{
value: 2,label: 'Running',color: '008000'
},{
value: 3,label: 'Rejected',color: 'cc0000'
},{
value: 4,label: 'Terminated',color: '2E9AFE'
}
]
}
},methods: {}
}
var Ctor = Vue.extend(Main);
new Ctor().$mount('#app');
@import url("//unpkg.com/element-ui@2.4.4/lib/theme-chalk/index.css");
.el-input--prefix .el-input__inner {
padding-left: 40px;
}
<script src="//unpkg.com/vue/dist/vue.js"></script>
<script src="//unpkg.com/element-ui@2.4.11/lib/index.js"></script>
<div id="app">
<el-select v-model="selectedState" value-key="value" style="width:200px">
<template slot="prefix">
<el-tag class="prefix" :style="`background-color: #${selectedState.color}`"/>
</template>
<el-option
v-for="state in processStates"
:key="state.value"
:label="state.label"
:value="state"
>
<span>
<el-tag :style="'background-color:#' + state.color"> </el-tag> {{ state.label }}
</span>
</el-option>
</el-select>
</div>