前言
在SvgIcon组件封装的介绍文档末尾提到了一些隐患问题,在这篇文档里做一个收尾。
关于SvgIcon组件封装问题,参考这篇:SvgIcon组件封装
问题展示
封装组件处理该问题
- 在
src/components
下创建组件如下:
<template>
<el-button
:type="type"
:plain="plain"
@mouseenter="enterBtn"
@mouseleave="leaveBtn"
>
// 前缀icon
<Svg-icon
v-if="icon && !suffix"
:name="icon"
:color="iconColor"
style="margin-right: 8px"
></Svg-icon>
// 默认插槽用于输入按钮文字
<slot></slot>
// 前缀icon
<Svg-icon
v-if="icon && suffix"
:name="icon"
:color="iconColor"
style="margin-left: 8px"
></Svg-icon>
</el-button>
</template>
<script setup>
import { ref } from "vue";
// 默认icon颜色
const iconColor = ref("#ffffff");
// 定义传参
const prop = defineProps({
type: {
type: String,
default: ""
},
icon: {
type: String,
default: ""
},
plain: {
type: Boolean,
default: false
},
suffix: {
type: Boolean,
default: false
}
});
// 处理在plain模式下,icon的特定关键字颜色,非plain模式下正常显示白色
const handleIconColor = () => {
// plain模式修改颜色,非plain模式不修改
if (prop.plain) {
switch (prop.type) {
case "primary":
iconColor.value = "#409eff";
break;
case "success":
iconColor.value = "#67c23a";
break;
case "info":
iconColor.value = "#909399";
break;
case "warning":
iconColor.value = "#e6a23c";
break;
case "danger":
iconColor.value = "#f56c6c";
break;
default:
iconColor.value = "#303133";
break;
}
}
};
handleIconColor();
// 处理鼠标移入按钮时icon颜色
const enterBtn = () => {
iconColor.value = "#ffffff";
};
// 处理鼠标移出按钮时icon颜色
const leaveBtn = () => {
handleIconColor();
};
</script>
- 设计逻辑
- 组件接收四参数:type表示原element的按钮状态关键字,icon表示icon名称,plain表示是否开启plain模式,suffix表示是否为后缀icon默认为前缀icon。
- 定义各按钮状态关键字下对应的颜色信息
- 对按钮设置鼠标移入移出事件,设置icon反色
- 使用方法
// 根据前后缀icon需求,决定是否填写suffix
<custom-btn icon="plus" type="primary" plain suffix>
按钮
</custom-btn>
// 不填写plain的情况下,这个组件就是个和原element button一致的带icon的按钮,默认icon为白色
<custom-btn icon="plus" type="primary">
按钮
</custom-btn>
处理后效果展示
注册全局组件
- 为了方便项目使用,建议将处理后的自定义按钮组件注册为全局组件,其他页面无需引入文件直接使用。
- 批量注册方法在上一篇文档中有详细介绍,可以回头看一眼。链接: 封装SvgIcon组件,注册为全局组件