You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue3+Element Plus如何带参数传递组件作为按钮icon属性

Vue新手问题:自定义组件作为Element Plus按钮的icon属性传入方案

我是Vue新手,现有一个简单的自定义组件MaterialIcon.vue:

<script lang="ts">
export default {
  props: ['iconname']
}
</script>

<template>
  <span class="material-icons-outlined md-18">{{iconname}}</span>
</template>

我想把这个组件作为图标传入el-button的icon属性,还要处理组件带参数的情况,该怎么写?比如下面这段代码里的???该填什么:

<el-button type="primary" title="Refresh" :icon="???"/>

我试过用插槽的写法,虽然能运行但有问题:

<el-button type="primary" title="Refresh">
  <material-icon icon_name="refresh"/>
</el-button>

一是按钮的loading功能本该替换图标为加载动画,结果加载动画会显示在自定义图标旁边,不是替换;二是这种插槽写法完全没体现组件封装的意义,直接写原生span就行,没必要用自定义组件。


正确实现方案

Element Plus的icon属性接受的是组件对象,要传递带参数的自定义组件,得用Vue的h渲染函数来创建组件实例并传入props。

直接使用h函数

在使用el-button的组件里,导入h和自定义的MaterialIcon组件,然后用h函数生成组件实例绑定到icon属性:

<script setup lang="ts">
import { h } from 'vue'
import MaterialIcon from './MaterialIcon.vue'
</script>

<template>
  <el-button 
    type="primary" 
    title="Refresh" 
    :icon="h(MaterialIcon, { iconname: 'refresh' })"
    :loading="true"
  />
</template>

这样写的话,按钮的loading状态会正确替换掉自定义图标,同时也保留了组件封装的优势。

封装成工具函数(方便复用)

如果需要多次使用,可以把创建图标的逻辑封装成工具函数:

// 比如新建utils/icon.ts文件
import { h } from 'vue'
import MaterialIcon from '../components/MaterialIcon.vue'

export const createMaterialIcon = (iconName: string) => {
  return h(MaterialIcon, { iconname: iconName })
}

然后在组件里导入使用:

<script setup lang="ts">
import { createMaterialIcon } from './utils/icon'
</script>

<template>
  <el-button 
    type="primary" 
    title="Refresh" 
    :icon="createMaterialIcon('refresh')"
    :loading="true"
  />
</template>

内容的提问来源于stack exchange,提问作者Dan C

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 08:05:36