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

如何在Element UI的el-button组件中使用变量绑定Material Design Icons图标

Element UI 集成 Material Design Icons 变量绑定方案

问题根因

你的写法存在两个核心问题导致不生效:

  • 没有使用v-bind(简写:)绑定icon属性,直接书写的icon=svgPath2、icon="svgPath1"都是传入固定字符串,而非对应变量的实际值
  • Element UI 原生icon属性仅支持识别内置的图标类名,本身不支持直接传入MDI提供的svg路径参数

解决方案

推荐使用el-button的默认插槽自定义嵌入svg图标实现,这种方式兼容性最好,不需要额外依赖:

<template>
  <el-button 
    class="record-btn" 
    circle 
    @click="AudioRecorded"
  >
    <!-- 直接在按钮插槽内嵌入svg渲染MDI图标 -->
    <svg width="1em" height="1em" viewBox="0 0 24 24" fill="currentColor" style="vertical-align: middle;">
      <path :d="isRecording ? svgPath2 : svgPath1" />
    </svg>
  </el-button>
</template>

<script>
import { mdiStop, mdiRecordRec } from '@mdi/js'; 
export default {
  data () {
    return {
      svgPath1: mdiRecordRec,
      svgPath2: mdiStop,
      isRecording: false,
    }
  },
  methods: {
    AudioRecorded() {
      this.isRecording = !this.isRecording
      // 补充你的原有业务逻辑
    }
  }
}
</script>

通用优化方案

如果项目中多处使用MDI图标,可以将上述svg逻辑封装为全局通用组件,减少重复代码:

<!-- 全局注册的MdiIcon公共组件 -->
<template>
  <svg width="1em" height="1em" viewBox="0 0 24 24" fill="currentColor" style="vertical-align: middle;">
    <path :d="path" />
  </svg>
</template>
<script>
export default {
  props: {
    path: {
      type: String,
      required: true
    }
  }
}
</script>

封装完成后使用时可以简化为如下写法:

<el-button class="record-btn" circle @click="AudioRecorded">
  <MdiIcon :path="isRecording ? svgPath2 : svgPath1" />
</el-button>

内容的提问来源于stack exchange,提问作者David Asturizaga Orias

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 14:36:04