element-plus中icon图标动态使用的方式

3,714 阅读1分钟

element-plus中icon图标动态使用的方式

全局注册

入口文件

import { createApp,createVNode } from "vue";
import * as Icons from "@element-plus/icons-vue";
import ElementPlus from "element-plus";
import "element-plus/dist/index.css";
import App from "./App.vue";

const app = createApp(App);
app.mount("#app");

// 全局注册
Object.keys(Icons).forEach((key) => {
  app.component(key, Icons[key]);
});
  
// Icon自定组件
const Icon = (props) => {
  const { icon } = props;
  return createVNode(Icons[icon]);
};
app.component("Icon", Icon);

使用动态组件

通过使用component动态组件的方式引入

<template>
    <component :is="iconName" class="myIcon"></component>
</template>
<script setup>
const iconName = 'Search'
</script>
<style scoped>
.myIcon {
   width: 50px;
   height: 50px;
}
</style>

使用自定义组件

通过自定义Icon组件的方式引入

<template>
    <Icon :icon="iconName" class="myIcon" />
</template>
<script setup>
const iconName = 'Search'
</script>
<style scoped>
.myIcon {
   width: 50px;
   height: 50px;
}
</style>