背景
项目中有一个小需求,下拉框中选择颜色后让el-select也显示对应的颜色,如下图,很丑但是产品怎么说我怎么做说是。我看了一些教程,发现虽然很多博客但是都没有解决问题,就记录一下实现方法吧。
同时项目中还有一个图标选择器,这也是我第一次处理,而且因为用处很少不进公司组件库,也在这里记录一下。
scss中使用js的变量
关键是使用:style声明,然后在scss中就可以通过var()进行使用
同时也需要注意,如果使用的是scss变量,则js变量绑定的值中一定要加上var()
代码如下:
<style lang="ts" setup>
const btnCssList = [
{
name: 'primary',
value: 'var(--el-color-primary)' // 此处需要使用var()包裹
}
];
</style>
<template>
<el-select
v-model="settingMaintainForm.btnCss"
class="btn-css"
:style="{ '--btn-css': btnCssList.find((item) => item.name === self.settingMaintainForm.btnCss)?.name || '' }"
clearable
>
<el-option v-for="color in btnCssList" :key="color.value" :value="color.name">
<el-tag class="mx-1" effect="dark" :type="color.name">{{ color.name }}</el-tag>
</el-option>
</el-select>
</template>
<style lang="scss" scoped>
.btn-css {
:deep(.el-input__inner) {
background-color: var(--btn-css);
color: #fff;
}
}
</style>
图标选择器
实现起来很简单,具体代码如下
<template>
<el-popover ref="popover" hide-after="0" placement="bottom" :width="300" trigger="click" @hide="handleHide">
<template #reference>
<el-input v-model="icoCssStr" placeholder="请选择图标" clearable>
<template #prepend>
<el-button :icon="icoCssStr" />
</template>
</el-input>
</template>
<!-- 图标选择 -->
<div>
<el-input v-model="filter" @input="handleFilter" />
<el-scrollbar>
<div class="ui-fas">
<div v-for="(item, id) in iconList" :key="id" class="ui-fas-item">
<el-button :icon="item" @click="handleChoose(item)" />
</div>
</div>
</el-scrollbar>
</div>
</el-popover>
</template>
<script lang="ts" setup>
import * as ElIcons from '@element-plus/icons-vue';
import { ref, watch } from 'vue';
const prop = withDefaults(
defineProps<{
icoCss: string | null;
}>(),
{}
);
const iconList = ref<any>(ElIcons);
const filter = ref('');
const popover = ref();
const icoCssStr = ref(prop.icoCss);
const emit = defineEmits(['handleChoose']);
watch(
() => prop.icoCss,
(v) => {
icoCssStr.value = v;
}
);
const handleChoose = (icon) => {
emit('handleChoose', filter.value ? icon : icon.name);
popover.value.hide();
};
const handleFilter = () => {
iconList.value = ElIcons[filter.value];
if (filter.value === '') iconList.value = ElIcons;
};
const handleHide = () => {
filter.value = '';
iconList.value = ElIcons;
};
</script>
<style lang="scss" scoped>
.ui-fas {
display: flex;
flex-wrap: wrap;
height: 200px;
&-item {
margin: 10px 10px;
}
}
</style>