前提:已创建vue项目,未创建请参考 https://www.toutiao.com/article/7398100974524449330/
步骤 1:在项目目录下,安装 Element UI(Element UI 是一个基于 Vue.js 的组件库,它提供了一套为开发者设计和实现用户界面的解决方案。Element UI 提供了大量预设计的组件,如按钮、输入框、选择器等,这可以帮助开发者快速构建应用程序界面。
Element ui的手册网站: https://element-plus.org/zh-CN/guide/installation.html )
操作:在vscode中打开项目根目录,按ctrl+~键打开终端,在终端中输入npm install element-plus --save
步骤2:在 main.js 中引入 Element Plus 和相关的样式(此方式是全局引入即将Element所有的组件引入):
import { createApp } from 'vue';
import App from './App.vue';
import router from './router'; // 导入路由
import ElementPlus from 'element-plus'; // 导入 Element Plus
import 'element-plus/dist/index.css'; // 导入 Element Plus 的 CSS 样式
// 创建 Vue 应用实例
const app = createApp(App);
// 使用路由
app.use(router);
// 使用 Element Plus 插件
app.use(ElementPlus);
// 挂载应用
app.mount('#app');
步骤3: 使用 Element Plus 组件
打开网站的“组件”界面,在左侧选择要添加的组件,如:按钮;在右侧出现各种样式的按钮,点击样式右下角的“<>”显示出源代码,复制源代进行调用。
实操:我们可以在新建一个dome.vue页面,使用一个按钮组件:
(1)创建新页面,选中views右击点击“新建文件”在文件中输入“dome.vue”
(2)选择按钮样式,这里我选择success按钮,复制相对应的代码<el-button type="success">Success</el-button>
(3)将代码添加到页面中
<template>
<el-button type="success">Success</el-button>
</template>
<script setup>
</script>
<style>
/* 这里可以添加样式 */
</style>
(4)添加路由,也可理解为设计网页的网址链接。
在router/index.js中映入dome地址
注意添加时一定不要忘记绿框处的逗号一定是英文状态下输入的
import Dome from '../views/dome.vue'
,
{
path: '/dome',
name: 'dome',
component: Dome
}
运行看效果
在终端输入npm run serve ,按住ctrl单击http://localhost:8080/,在浏览器网址栏中的输入网址http://localhost:8080/#/dome
5. 配置按需引入(可选,小白尽量选择全局安装)
1. 安装 Element Plus 和 Babel 插件
首先,确保你已经安装了 Element Plus 和按需引入的 Babel 插件。
复制代码
npm install element-plus
npm install -D babel-plugin-import
2. 配置 main.js
import { createApp } from 'vue';
import App from './App.vue';
import router from './router';
const app = createApp(App);
app.use(router);
app.mount('#app');
babel.config.js
3. 配置 Babel
在 babel.config.js 中配置 babel-plugin-import 插件,以便按需引入 Element Plus 组件和样式:
module.exports = {
presets: [
'@vue/cli-plugin-babel/preset'
],
plugins: [
[
'import',
{
libraryName: 'element-plus',
customStyleName: (name) => {
return `element-plus/theme-chalk/${name}.css`;
},
},
'element-plus'
]
]
};
4. 按需引入组件
在你的 Vue 组件中按需引入 Element Plus 组件和相应的样式。例如,创建一个名为 Dome.vue 的组件并按需引入 ElButton 组件:
<template>
<el-button type="success">Success</el-button>
</template>
<script setup>
import { ElButton } from 'element-plus';
// 按需引入样式
import 'element-plus/theme-chalk/el-button.css';
</script>
<style scoped>
/* 这里可以添加局部样式 */
</style>