element-plus 按需导入与全局导入
哈哈与黑洞大笑 人气:0按需导入:
安装插件
首先需要引入额外的插件:前**vite-plugin-components
已重命名为unplugin-vue-components
**
npm install unplugin-vue-components
配置插件
在weapack或vite配置文件内中添加配置
// vite.config.ts import Components from 'unplugin-vue-components/vite' import { ElementPlusResolver } from 'unplugin-vue-components/resolvers' export default { plugins: [ // ... Components({ resolvers: [ElementPlusResolver()], }), ], }
// webpack.config.js const Components = require('unplugin-vue-components/webpack') const { ElementPlusResolver } = require('unplugin-vue-components/resolvers') module.exports = { // ... plugins: [ Components({ resolvers: [ElementPlusResolver()], }), ], }
//main.ts import { createApp } from 'vue' import App from './App.vue' import { Edit,Search } from '@element-plus/icons' //图标需要分开导入,按需导入图标 import { ElButton } from 'element-plus'; //按需导入 const app = createApp(App); //注册组件 app.component("edit", Edit) app.component("search", Search) app.component('ElButton',ElButton) app.mount('#app');
<template> <h2>home页面</h2> <el-button type="primary" >主要按钮</el-button> <el-button type="success" >成功按钮</el-button> <el-icon :size="20" :color="'blue'"> <edit /> </el-icon> <el-icon :size="20"> <search></search> </el-icon> </template> <script setup lang="ts"> </script>
全局导入
推荐添加
// tsconfig.json { "compilerOptions": { // ... "types": ["element-plus/global"] } }
安装
npm install element-plus --save # or yarn add element-plus # 安装icon图标依赖库 npm install @element-plus/icons # or yarn add @element-plus/icons
在main.ts 文件中全局配置
import { createApp } from 'vue' import App from './App.vue' import { store, key } from './store'; // 注入路由 import router from './router'; // 全局引入ui库 import ElementPlus from 'element-plus' import 'element-plus/dist/index.css' const app = createApp(App); app.use(store, key); app.use(router); app.use(ElementPlus); app.mount('#app');
使用ui组件
使用图标,因为图标和普通ui组件不是同一个包,使用需要分别导入
//导入具体的组件后直接使用 <template> <el-icon :size="20" :color="'blue'"> <edit /> </el-icon> </template> <script setup lang="ts"> import { Edit } from '@element-plus/icons' </script>
将图标库在main.ts文件中impott并使用app.component()注册便可以直接在组件中使用了,和普通的使用ui库同理
<template> <h2>home页面</h2> <el-button type="primary" >主要按钮</el-button> <el-button type="success" >成功按钮</el-button> <el-icon :size="20" :color="'blue'"> <edit /> </el-icon> <el-icon :size="20"> <search></search> </el-icon> </template> <script setup lang="ts"> </script>
加载全部内容