您的当前位置:首页>全部文章>文章详情

Element-plus,动态添加图标的方式

发表于:2022-02-23 18:28:45浏览:3778次TAG: #ElementUI #添加图标 #Vue

element-plus里面的icon,以前是字符串形式的,非常容易做成动态的效果,但是最新版本改成了组件的形式,不支持字符串的形式了。那么对于组件形式如何动态添加图标呢?
其实也很简单,我们把需要的icon组件注册为全局的字典,key:组件的形式,然后就可以把字符串转换为图标组件了。

全局注册

首先建立一个js文件,引入图标,做成字典的形式,再用 Vue 的插件功能注册为全局变量。
\src\icon\index.js

import { reactive } from 'vue'
/*
// 引入全部图标
 import * as Icons from "@element-plus/icons"
 const ggIcon = Icons
*/

// 按需引入图标
import {
  CloseBold,
  Close,
  Plus,
  Star,
  UserFilled,
  Loading,
  Connection,
  Check,
  Edit,
  Delete,
  FolderOpened
} from '@element-plus/icons'


const ggIcon = reactive({
  CloseBold,
  Close,
  Plus,
  Star,
  UserFilled,
  Loading,
  Connection,
  Check,
  Edit,
  Delete,
  FolderOpened
})
export default ggIcon

1、使用全部图标
这里有两种使用方式,一种是简单粗暴的全部图标都注册了,看了一下node_modules里面的文件,一共二、三百KB,如果你不太在意代码体积的话,可以全都弄进来。(上面代码已注释掉)
2、按需获取
如果使用的图标不是很多,那么可以只引入需要的图标,这样体积就小很多了。

挂载

然后在 main.js 里面挂载,代码如下:

import ggIcon from "./icon/index";
app.config.globalProperties.$icon = ggIcon;

使用

最后在项目中使用,下面列举几个常见的例子:
1、在模板里面使用:

<component
  :is="$icon[iconName]"
  style="width: 1.5em; height: 1.5em; margin-right: 8px;color:#123456"
>
</component>

在模板里面使用动态组件,根据图标名称加载图标,使用style设置大小和颜色,这样就可以了。
2、在组件属性里面使用

<el-input
    v-model="value"
    :prefix-icon="($icon)?$icon['Edit']:'' "
    :suffix-icon="($icon)?$icon[iconName]:'' "
>
</el-input>

el-input 的 prefix-icon 属性可以设置图标,属性类型是字符串或者组件,试了一下字符串,没有效果,大概需要在使用 el-input 的组件里面注册对应的图标,这样就不方便实现动态图标了,或者全局注册图标。
3、在button中使用

<div class="header">
   <el-button type="primary" @click="handleAdd" :icon="$icon.Delete">增加</el-button>
   <el-popconfirm
      title="确定删除吗?"
      @confirm="handleDelete"
   >
       <template #reference>
          <el-button type="danger" :icon="$icon.Delete">批量删除</el-button>
       </template>
   </el-popconfirm>
</div>