Element Plus的Result组件如何自定义图标样式?

司徒景荣 阅读 42

我在用Element Plus的Result组件做操作反馈页时,想把默认的成功图标换成其他图标,但直接设置icon属性没效果。试过用icon插槽手动放svg图标,虽然显示出来了但位置不对,总是偏移到右下角。

还尝试过注册全局图标组件,但控制台报Unknown icon name: custom-icon错误。该怎么正确替换Result的图标样式呢?

<el-result
  icon="success"
  title="操作成功"
>
  <template #icon>
    <svg class="custom-svg" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024">...</svg>
  </template>
</el-result>
我来解答 赞 9 收藏
二维码
手机扫码查看
2 条解答
闲人德丽
你这个问题主要是两个点没处理好,一个是插槽的样式覆盖,另一个是图标注册方式。

首先直接用 template#icon 插入 SVG 是可以的,但 Element Plus 的 Result 组件默认会给图标加一些定位样式,你的 SVG 被挤到右下角是因为外层有个 .el-result__icon 包裹元素自带 text-align: center 和 position: relative,而你的 svg 没有设置宽高和居中对齐,导致布局错乱。

更优雅的做法是用 ElIcon 包一层,并控制样式:

<el-result title="操作成功">
<template #icon>
<el-icon class="custom-result-icon">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024" class="icon-svg">
<!-- 你的路径 -->
</svg>
</el-icon>
</template>
</el-result>


然后补上样式让它居中显示:

.custom-result-icon {
font-size: 64px;
width: 64px;
height: 64px;
}
.icon-svg {
width: 100%;
height: 100%;
fill: currentColor;
}


如果你打算复用这个图标,推荐注册成全局组件。报 Unknown icon name 错是因为你没正确注册。比如用 @element-plus/icons-vue 里的模式:

import { createApp } from 'vue'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'

const app = createApp(App)
for (const [name, component] of Object.entries(ElementPlusIconsVue)) {
app.component(name, component)
}

// 然后自定义图标也要手动注册
app.component('CustomSuccess', CustomSuccessIcon)


之后就可以在 result 里写 icon="CustomSuccess" 了,前提是这个组件已注册且命名规范匹配。

不过最简单的方案其实是不用 icon 属性,坚持用 #icon 插槽 + 上面的样式调整,避免走内置 icon 解析逻辑,这样自由度更高也更稳定。

可以优化成封装一个 CustomResult 组件,把图标逻辑收进去,以后多个页面都好维护。
点赞 6
2026-02-11 20:08
上官利伟
直接用 #icon 插槽没问题,但你需要手动调整样式来对齐位置。Element Plus 默认的图标有内置样式,你自己放的 SVG 没继承这些样式,所以会跑偏。

复制这个代码,把你的 SVG 内容粘进去就行:

<el-result
title="操作成功"
>
<template #icon>
<div class="custom-icon-wrapper">
<svg class="custom-svg" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024">
...你的 SVG 路径...
</svg>
</div>
</template>
</el-result>

<style scoped>
.custom-icon-wrapper {
display: flex;
justify-content: center;
align-items: center;
width: 64px;
height: 64px;
}
.custom-svg {
width: 100%;
height: 100%;
}
</style>


关键是给 SVG 包一层容器,然后用 flex 把它居中对齐。这样就不会跑到右下角了。懒得折腾的话,就直接用 Element 自带的图标算了,省心。
点赞 9
2026-01-29 14:00