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

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


PS:在本页按F12,在console中输入document.querySelectorAll('.diggit')[0].click(),有惊喜哦


面向百度编程

公众号

weixinQRcode.png

往期文章

个人主页

posted @ 2021-11-29 09:30  鹏多多  阅读(7507)  评论(0编辑  收藏  举报