安装准备
先安装elementplus
npm install element-plus --save
安装自动导入的插件
npm install -D unplugin-vue-components unplugin-auto-import
配置vue.config.js
const AutoImport = require('unplugin-auto-import/webpack')
const Components = require('unplugin-vue-components/webpack')
const { ElementPlusResolver } = require('unplugin-vue-components/resolvers')
module.exports = {
outputDir: './dist', // 打包导出地址
configureWebpack: {
resolve: {
alias: {
views: '@/views'
}
},
plugins: [
AutoImport({
resolvers: [ElementPlusResolver()],
}),
Components({
resolvers: [ElementPlusResolver()],
}),
],
}
}
main.ts
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
// 按需要引入 element-plus
import { globalRegister } from './gloable'
const app = createApp(App)
// 注册element-plus/其他
app.use(globalRegister)
app.use(store)
app.use(router)
app.mount('#app')
auto-imports.d.ts
这个是插件自动生成的文件
当我们引用组件时就会发现会在src目录下多出一个这个文件,这个文件就是动态帮助我们引用用到的组件。但是当我们删除组件时它不会删除,所以当我们删除时还需要到该文件下删除哦!!
// Generated by 'unplugin-auto-import'
// We suggest you to commit this file into source control
declare global {
const ElAffix: typeof import('element-plus/es')['ElAffix']
const ElAvatar: typeof import('element-plus/es')['ElAvatar']
const ElBadge: typeof import('element-plus/es')['ElBadge']
const ElButton: typeof import('element-plus/es')['ElButton']
}
export {}
gloable文件夹下的index.ts
这个是自己建个gloable文件夹
import { App } from 'vue'
import registerElementIcons from './regiter-element-icons'
//app.use 默认执行其中的函数并且传入app对象
export function globalRegister(app: App): void {
app.use(registerElementIcons)
}
gloable文件夹下的regiter-element-icon
import type { App } from 'vue'
import { Edit, Search, AddLocation } from '@element-plus/icons-vue'
export const icons = [Edit, Search, AddLocation]
//按需导出图标组件
export default function (app: App): void {
for (const icon of icons) {
app.component(icon.name, icon)
}
}
使用 main.vue
<template>
<div id="nav">
<el-button type="danger">Danger</el-button>
<el-icon :size="20" :color="'blue'">
<edit />
</el-icon>
<el-icon :size="20">
<search></search>
</el-icon>
<edit></edit>
<el-icon><add-location /></el-icon>
<el-button type="primary" :icon="Edit" circle></el-button>
<el-input v-model="input" placeholder="Please input" clearable />
</div>
<router-view />
</template>
<script lang="ts">
import { defineComponent, ref } from 'vue'
import { Edit } from '@element-plus/icons-vue'
export default defineComponent({
setup() {
//使用属性icon添加图标时需要引入
return {
input: ref(''),
Edit
}
}
})
</script>
后面我们只需要在regiter-element-icon添加用到的图标就可以实现按需导入了!