09vue3实战-----引入element-plus组件库中的图标
- 1.安装
- 2.引入
- 3.优化
element-plus中的icon图标组件的使用和其他平台组件(如el-button按钮)是不一样的。
1.安装
npm install @element-plus/icons-vue
2.引入
在这我们只讲述最方便的一种引入方法------完整引入。这需要从@element-plus/icons-vue 中导入所有图标并进行全局注册
main.ts:
// 如果您正在使用CDN引入,请删除下面一行。
import * as ElementPlusIconsVue from '@element-plus/icons-vue'const app = createApp(App)
//循环遍历图标组件数组
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {app.component(key, component)
}
3.优化
在大型项目中,经常需要注册各类组件库或者插件。如果把代码都写在main.ts,当项目很大时候可能该文件会比较复杂。可以把上述注册所有图标组件的代码抽离成一个文件来解决该问题。
新建global文件夹,在此基础上新建一个ts文件来注册图标组件:
register-icons.ts:
import type { App } from 'vue'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'function registerIcons(app: App<Element>) {for (const [key, component] of Object.entries(ElementPlusIconsVue)) {app.component(key, component)}
}export default registerIcons;
上面的代码中需要注意registerIcons函数中传入的app,需要知道app的类型。自从使用了ts之后,相信很多人都对很多比较复杂的对象的类型不是清楚,比如这里的app。我们可以ctrl+鼠标左键点击main.ts文件中的createApp进入源码。
再ctrl+鼠标左键点击CreateAppFunction:
发现该函数为App类型,而且带有一个泛型。所以此处的代码如下:
然后再main.ts中注册:
import { createApp } from 'vue'
import App from './App.vue'
import registerIcons from './global/register-icons'const app = createApp(App)
app.use(registerIcons)app.mount('#app')