Vue3+TS使用element-plus 动态Icon图标

目录

  • 1,前言
  • 2,使用
    • 2.1,方式一
    • 2.2,方式二

1,前言


源于一段话

Element Plus 团队正在将原有组件内的 Font Icon 向 SVG Icon 迁移,请多多留意更新日志, 及时获取到更新信息,Font Icon 将会在第一个正式发布被废弃,请尽快迁移

在此记录一下如何使用element-plus中的icon组件

环境:

  • Vue:3.2.16
  • Element-Plus:1.2.0-beta.3
  • TypeScript:4.4.3
  • Vite:2.6.4

2,使用


文档原话:如果你想像用例一样直接使用,你需要全局注册组件,才能够直接在项目里使用

main.ts中先导入

import * as Icons from '@element-plus/icons'

2.1,方式一


main.ts

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import { store, key } from './store'
import * as Icons from '@element-plus/icons'

const app = createApp(App)
app.use(store, key)
app.use(router)
app.mount('#app')

// 注册全局组件
Object.keys(Icons).forEach(key => {
  app.component(key, Icons[key as keyof typeof Icons])
})

xxx.vue文件中

// html
<template>
   <el-icon :size="20"><alarm-clock /></el-icon>
</template>

或使用动态组件

// html
<template>
  <component class="xxx" :is="iconName"></component>
</template>
// script
export default {
  name: 'Login',
  setup() {
    const iconName = 'Search'
    return {
      iconName
    }
  }
}

2.2,方式二


main.ts

import { createApp, createVNode } from 'vue'
import App from './App.vue'
import router from './router'
import { store, key } from './store'
import * as Icons from '@element-plus/icons'

const app = createApp(App)
app.use(store, key)
app.use(router)
app.mount('#app')

// 创建Icon组件
const Icon = (props: { icon: string }) => {
  const { icon } = props
  return createVNode(Icons[icon as keyof typeof Icons])
}
// 注册Icon组件
app.component('Icon', Icon)

使用动态组件

// html
<template>
  <Icon class="xxx" :icon="iconName"></Icon>
</template>
// script
export default {
  name: 'Login',
  setup() {
    const iconName = 'Search'
    return {
      iconName
    }
  }
}

如果看了觉得有帮助的,我是@上进的鹏多多,欢迎 点赞 关注 评论;
END

往期文章

  • 助你上手Vue3全家桶之Vue3教程
  • 助你上手Vue3全家桶之VueX4教程
  • 助你上手Vue3全家桶之Vue-Router4教程
  • 超详细!Vue的九种通信方式
  • 超详细!Vuex手把手教程
  • 使用nvm管理node.js版本以及更换npm淘宝镜像源
  • vue中利用.env文件存储全局环境变量,以及配置vue启动和打包命令
  • 超详细!Vue-Router手把手教程

个人主页

  • CSDN
  • GitHub
  • 简书
  • 博客园
  • 掘金

你可能感兴趣的:(Vue,vue.js,前端)