
📃个人主页:编程的一拳超人
⛺️ 欢迎关注:👍点赞 👂🏽留言 😍收藏 💞 💞 💞
坚如磐石的信心、只争朝夕的劲头、坚韧不拔的毅力。 ——《人民日报》
基于Vue2与3版本的Element UI与Element Plus入门
Element UI 入门
Element UI 是基于 Vue 2.0 的桌面端组件库,它提供了一系列配套的组件和布局,帮助开发者快速构建功能丰富、美观大方的网页界面。
安装
通过 npm 安装 Element UI:
npm i element-ui -S
引入 Element UI
在 Vue 项目中,可以通过以下几种方式引入 Element UI:
- 完整引入:
import Vue from 'vue';
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
Vue.use(ElementUI);
- 按需引入(推荐):
首先,安装babel-plugin-component
:
npm install babel-plugin-component -D
然后,在 .babelrc
或 babel.config.js
文件中添加配置:
{
"plugins": [
[
"component",
{
"libraryName": "element-ui",
"styleLibraryName": "theme-chalk"
}
]
]
}
最后,在 main.js 中按需引入组件:
import Vue from 'vue';
import { Button, Select } from 'element-ui';
import App from './App.vue';
Vue.component(Button.name, Button);
Vue.component(Select.name, Select);
new Vue({
el: '#app',
render: h => h(App)
});
使用组件
在 Vue 模板中,可以直接使用 Element UI 的组件:
<template>
<el-button @click="handleClick" type="primary">主要按钮</el-button>
</template>
<script>
export default {
methods: {
handleClick() {
console.log('按钮被点击');
}
}
};
</script>
Element Plus 入门
Element Plus 是 Element UI 的 Vue 3 版本,提供了与 Element UI 类似的功能和组件,但针对 Vue 3 进行了优化和适配。
安装
通过 npm 安装 Element Plus:
npm install element-plus --save
引入 Element Plus
在 Vue 3 项目中,可以通过以下几种方式引入 Element Plus:
- 完整引入:
import { createApp } from 'vue'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import App from './App.vue'
const app = createApp(App)
app.use(ElementPlus)
app.mount('#app')
- 按需引入:
首先,你需要安装unplugin-vue-components
和unplugin-auto-import
这两个插件来支持按需引入:
npm install -D unplugin-vue-components unplugin-auto-import
然后,在 Vue CLI 或 Vite 的配置文件中添加插件配置:
// vite.config.js
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
export default defineConfig({
plugins: [
vue(),
AutoImport({
resolvers: [ElementPlusResolver()],
}),
Components({
resolvers: [ElementPlusResolver()],
}),
],
})
使用组件
在 Vue 模板中,可以直接使用 Element Plus 的组件:
<template>
<el-button @click="handleClick" type="primary">主要按钮</el-button>
</template>
<script setup>
import { ref } from 'vue'
const handleClick = () => {
console.log('按钮被点击');
}
</script>
常用组件
Element UI 和 Element Plus 包含许多常用的组件,如:
- Button(按钮)
- Input(输入框)
- Select(选择器)
- Table(表格)
- Pagination(分页)
- Dialog(对话框)
- Form(表单)
每个组件都有详细的文档和示例,方便开发者查阅和使用。
自定义主题
Element UI 和 Element Plus 都支持自定义主题。你可以通过修改 SCSS 变量来定制主题,也可以使用在线主题生成工具来生成。
兼容性和升级
由于 Element UI 是基于 Vue 2.0 的,因此在使用 Vue 3.0 的项目中,你可能需要考虑使用 Element Plus。同样地,如果你正在使用 Vue 2.0,你应该使用 Element UI。
社区和支持
Element UI 和 Element Plus 都有庞大的社区和良好的文档支持,开发者可以方便地找到问题解决方案和最佳实践。
通过以上步骤,你可以快速地开始使用 Element UI 或 Element Plus 来构建你的 Vue 应用。