Element Plus动态Icon的使用方法

需要先学习这两个前置知识。

Icon 图标 | Element Plus

组件基础 | Vue.js

Icon 的基本使用方式

安装

npm install @element-plus/icons

在script标签中引入要使用的icon

import {
    
     Fold } from '@element-plus/icons'

在template标签中使用icon

<el-icon>
	<Fold />
</el-icon>

动态 Icon 的使用方式

  • 方式一

    // 在main.ts注册Icon组件
    import * as Icons from '@element-plus/icons'
    
    const app = createApp(App)
    Object.keys(Icons).forEach((key) => {
          
          
    	app.componet(key, Icons[key as keyof typeof Icons])
      	// app.componet(key, Icons[key]) 等价于上面这行
    })
    
    // 使用Icon组件
    <component :is="Fold"></component>
    
  • 方式二

    // 在main.ts注册Icon组件
    import * as Icons from '@element-plus/icons'
    
    const app = createApp(App)
    const Icon = (props: {
          
          icon : string}) => {
          
          
      const {
          
           icon } = props;
      return createVNode(Icons[icon as keyof typeof Icons]);
    }
    app.component('Icon', Icon);
    
    // 使用Icon组件
    <component :is="Fold"></component>
    
  • 方式三(官方)

    // 在main.ts注册Icon组件
    import * as ElementPlusIconsVue from '@element-plus/icons-vue'
    
    const app = createApp(App)
    for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
          
          
      app.component(key, component)
    }
    
    // 使用Icon组件
    <component :is="Fold"></component>
    

猜你喜欢

转载自blog.csdn.net/qq_43492356/article/details/127615443