当前位置: 首页 > news >正文

【学习总结|DAY036】Vue工程化+ElementPlus

引言

在前端开发领域,Vue 作为一款流行的 JavaScript 框架,结合 ElementPlus 组件库,为开发者提供了强大的构建用户界面的能力。本文将结合学习内容,详细介绍 Vue 工程化开发流程以及 ElementPlus 的使用,助力开发者快速上手并应用到实际项目中,且会包含丰富的代码案例以便更好地理解和实践。

一、Vue 基础与工程化

(一)Vue 框架概述

Vue 是一款用于构建用户界面的渐进式 JavaScript 框架,它不仅是一个框架,还拥有丰富的生态。其核心功能包括声明式渲染、组件系统、客户端路由(VueRouter)、状态管理(Pinia、Vuex)等,官方网站为开发者提供了全面的文档支持(https://cn.vuejs.org/) 。

(二)Vue 工程化概念

前端工程化旨在企业级项目开发中,将前端开发所需的工具、技术、流程和经验进行规范化、标准化,涵盖模块化、组件化、规范化和自动化等方面。Vue 工程化则是基于 Vue 框架实现这些特性,提升开发效率、代码复用性和可维护性。

(三)Vue 工程化环境搭建与项目创建

  1. 环境准备:使用 Vue 官方提供的脚手架工具 create-vue,需要先安装 NodeJS(一个免费、开源、跨平台的 JavaScript 运行时环境),并通过其软件包管理器 npm 进行后续操作。
  2. 创建项目:执行npm create vue@3.3.4命令,根据提示设置项目名称、是否添加 TypeScript、JSX 支持、Vue Router、Pinia、测试工具(Vitest、Cypress)以及 ESLint 代码质量检查等功能。例如,创建一个名为my - vue - project的项目,不添加 TypeScript、JSX 支持,添加 Vue Router 和 Pinia:
C:\Users\YourUsername\Desktop>npm create vue@3.3.4
npx create - vue
Vue.js - The Progressive JavaScript Framework
Project name:...my - vue - project
Add TypeScript?... No
Add JSX Support? ...No
Add Vue Router for Single Page Application development?...Yes
Add Pinia for state management?... Yes
Add Vitest for Unit Testing?...No
Add Cypress for both Unit and End - to - End testing?... No
Add ESLint for code quality?...No
Scaffolding project in C:\Users\YourUsername\Desktop\my - vue - project...
Done. Now run:
cd my - vue - project
npm install
npm run dev

  1. 安装依赖与启动项目:进入项目目录,执行npm install安装项目依赖,再通过npm run dev启动项目,在浏览器中访问http://localhost:5173即可查看项目。

(四)Vue 项目开发流程与结构

  1. 项目结构剖析:Vue 项目包含.vscode(开发工具配置)、node_modules(第三方包)、public(静态资源)、src(源代码)等目录。其中,src目录下的main.js是入口文件,负责创建 Vue 应用实例;App.vue是根组件,.vue文件为单文件组件,将组件的逻辑(JS)、模板(HTML)和样式(CSS)封装在一起。
  2. 开发流程梳理:开发过程中,在单文件组件中编写代码。例如,在App.vue中,<script setup>部分定义数据和方法,<template>部分生成 HTML 结构,<style scoped>部分定义组件的 CSS 样式。以下是一个简单的App.vue示例:
<template><div><h1>{{ message }}</h1><button @click="increment">点击计数: {{ count }}</button></div>
</template><script setup>
import { ref } from 'vue';const message = ref('欢迎来到Vue项目');
const count = ref(0);const increment = () => {count.value++;
};
</script><style scoped>
h1 {color: blue;
}
</style>

(五)Vue API 风格

Vue 组件有选项式 API 和组合式 API 两种风格。

  1. 选项式 API:通过包含datamethodsmounted等选项的对象描述组件逻辑,这些选项定义的属性可通过this指向当前组件实例访问。示例代码如下:
<template><button @click="increment">count:{{ count }}</button>
</template><script>
export default {data() {return {count: 0};},methods: {increment() {this.count++;}},mounted() {console.log('Vue mounted...');}
};
</script>

  1. 组合式 API:Vue3 引入的基于函数的组件编写方式,使用ref()创建响应式变量,onMounted()注册组件挂载后的回调函数,setup标识开启组合式 API 的简洁使用方式,且在组合式 API 中thisundefined。示例代码如下:
<template><button @click="increment">count:{{ count }}</button>
</template><script setup>
import { ref, onMounted } from 'vue';const count = ref(0);const increment = () => {count.value++;
};onMounted(() => {console.log('Vue Mounted...');
});
</script>

二、ElementPlus 组件库

(一)ElementPlus 简介

ElementPlus 是饿了么团队基于 Vue 3 研发的组件库,提供了丰富的组件,如按钮、表单、表格等,官网为https://element-plus.org/zh-CN/#/zh-CN 。

(二)ElementPlus 快速入门

  1. 安装与引入:在项目目录下执行npm install element-plus@2.4.4 --save安装组件库,在main.js中引入 ElementPlus 及其样式:
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).mount('#app');

  1. 组件使用:访问 ElementPlus 官方文档,复制所需组件代码并根据项目需求调整。例如,使用按钮组件:
<template><el - button type="primary">主要按钮</el - button><el - button type="success">成功按钮</el - button>
</template><script setup>
// 无需额外导入,直接使用ElementPlus组件
</script>

(三)ElementPlus 常见组件

  1. 表格组件:用于展示多条结构类似的数据,使用时需明确绑定的数据data和每列展示的属性信息。以下是一个结合异步数据获取的表格示例:
<template><el - table :data="tableData" style="width: 100%"><el - table - column prop="date" label="日期" width="180"></el - table - column><el - table - column prop="name" label="姓名" width="180"></el - table - column><el - table - column prop="address" label="地址"></el - table - column></el - table>
</template><script setup>
import { ref, onMounted } from 'vue';
import axios from 'axios';const tableData = ref([]);const fetchData = async () => {try {const response = await axios.get('https://example.com/api/data');tableData.value = response.data;} catch (error) {console.error('数据获取失败:', error);}
};onMounted(() => {fetchData();
});
</script>

  1. 分页条组件:当数据量过多时进行分页操作,可配置属性和事件,如需使用中文,可引入中文语言包进行配置。示例代码如下:
<template><div><el - pagination:total="total":page - size="pageSize":current - page="currentPage"@current - change="handleCurrentChange"layout="prev, pager, next"></el - pagination></div>
</template><script setup>
import { ref } from 'vue';
import zhCn from 'element-plus/dist/locale/zh-cn.mjs';
import { createApp } from 'vue';
import ElementPlus from 'element-plus';
import App from './App.vue';const app = createApp(App);
app.use(ElementPlus, { locale: zhCn }).mount('#app');const total = ref(400);
const pageSize = ref(10);
const currentPage = ref(1);const handleCurrentChange = (page) => {currentPage.value = page;// 在此处可根据当前页码重新请求数据
};
</script>

  1. 对话框组件:在保留页面状态下告知用户并承载相关操作,通过model-value/v-model绑定的布尔值控制显示与隐藏。示例代码如下:
<template><div><el - button @click="dialogVisible = true">打开对话框</el - button><el - dialog v - model="dialogVisible" title="提示"><p>这是一个对话框内容</p><template #footer><el - button @click="dialogVisible = false">关闭</el - button></template></el - dialog></div>
</template><script setup>
import { ref } from 'vue';const dialogVisible = ref(false);
</script>

  1. 表单组件:包含输入框、单选框等多种输入组件,用于收集、验证和提交数据,关键在于表单项布局、数据采集(v-model绑定)和数据提交(事件绑定)。示例代码如下:
<template><el - form ref="formRef" :model="formData" label - width="80px"><el - form - item label="活动名称"><el - input v - model="formData.activityName"></el - input></el - form - item><el - form - item label="活动区域"><el - select v - model="formData.activityZone"><el - option label="区域一" value="zone1"></el - option><el - option label="区域二" value="zone2"></el - option></el - select></el - form - item><el - form - item><el - button type="primary" @click="submitForm">提交</el - button><el - button @click="resetForm">重置</el - button></el - form - item></el - form>
</template><script setup>
import { ref } from 'vue';const formRef = ref();
const formData = ref({activityName: '',activityZone: ''
});const submitForm = () => {formRef.value.validate((valid) => {if (valid) {console.log('表单提交成功', formData.value);} else {console.log('表单验证失败');}});
};const resetForm = () => {formRef.value.resetFields();
};
</script>

三、实战案例

(一)Vue 项目中数据渲染案例

在 Vue 项目中基于组合式 API 完成用户列表数据渲染。首先安装axios依赖用于发起异步请求,在组件中引入相关函数和axios,定义响应式变量和请求方法,在onMounted钩子函数中触发请求获取数据并渲染。示例代码如下:

<template><table border="1" cellspacing="0" width="60%"><thead><tr><th>编号</th><th>姓名</th><th>年龄</th><th>性别</th><th>成绩</th><th>等级</th></tr></thead><tbody><tr v - for="(user, index) in userList" :key="index"><td>{{ index + 1 }}</td><td>{{ user.name }}</td><td>{{ user.age }}</td><td><span v - if="user.gender === 1">男</span><span v - if="user.gender === 2">女</span></td><td>{{ user.score }}</td><td><span v - if="user.score >= 85">优秀</span><span v - else - if="user.score >= 60">及格</span><span style="color: red;" v - else>不及格</span></td></tr></tbody></table>
</template><script setup>
import { ref, onMounted } from 'vue';
import axios from 'axios';const userList = ref([]);const fetchUsers = async () => {try {const response = await axios.get('https://web-server.itheima.net/emps/list');userList.value = response.data.data;} catch (error) {console.error('用户数据获取失败:', error);}
};onMounted(() => {fetchUsers();
});
</script>

(二)ElementPlus 综合案例

利用 ElementPlus 制作包含查询、表单、表格等元素的页面,并异步获取数据展示。结合 ElementPlus 组件的使用方法,通过配置和代码编写实现页面功能。示例代码如下:

<template><div><el - form :model="queryForm" label - width="80px" class="query - form"><el - form - item label="姓名"><el - input v - model="queryForm.name"></el - input></el - form - item><el - form - item label="性别"><el - select v - model="queryForm.gender"><el - option label="全部" value=""></el - option><el - option label="男" value="1"></el - option><el - option label="女" value="2"></el - option></el - select></el - form - item><el - form - item><el - button type="primary" @click="searchUsers">查询</el - button><el - button @click="resetQuery">清空</el - button></el - form - item></el - form><el - table :data="userList" style="width: 100%"><el - table - column prop="name" label="姓名" width="180"></el - table - column><el - table - column prop="gender" label="性别" width="80"><template #default="scope"><span v - if="scope.row.gender === 1">男</span><span v - if="scope.row.gender === 2">女</span></template></el - table - column><el - table - column prop="job" label="职位" width="180"></el - table - column><el - table - column prop="hireDate" label="入职日期" width="180"></el - table - column><el - table - column prop="updateDate" label="更新时间" width="180"></el - table - column></el - table></div>
</template><script setup>
import { ref, onMounted } from 'vue';
import axios from 'axios';const queryForm = ref({name: '',gender: ''
});
const userList = ref([]);const searchUsers = async () => {try {const response = await axios.get(`https://web-server.itheima.net/emps/list?name=${queryForm.value.name}&gender=${queryForm.value.gender}`);userList.value = response.data.data;} catch (error) {console.error('用户数据查询失败:', error);}
};const resetQuery = () => {queryForm.value.name = '';queryForm.value.gender = '';searchUsers();
};onMounted(() => {searchUsers();
});
</script><style scoped>
.query - form {margin - bottom: 20px;
}
</style>

四、总结

Vue 工程化开发与 ElementPlus 组件库的结合,为前端开发者提供了高效的开发方式。通过规范化的项目结构、灵活的 API 风格以及丰富的组件库,开发者能够快速构建出功能强大、用户体验良好的前端应用。在实际开发中,不断深入学习和实践,将这些技术运用到更多项目中,提升自己的前端开发能力。

http://www.lryc.cn/news/532938.html

相关文章:

  • 【GitHub】GitHub 2FA 双因素认证 ( 使用 Microsoft Authenticator 应用进行二次验证 )
  • c# 2025/2/7 周五
  • 蓝桥杯思维训练(五)
  • I.MX6ULL 中断介绍下
  • Elasticsearch 生产集群部署终极方案
  • Python用langchain、OpenAI大语言模型LLM情感分析苹果股票新闻数据及提示工程优化应用...
  • 【正点原子K210连载】第六十七章 音频FFT实验 摘自【正点原子】DNK210使用指南-CanMV版指南
  • Centos Ollama + Deepseek-r1+Chatbox运行环境搭建
  • ReactNative进阶(五十九):存量 react-native 项目适配 HarmonyOS NEXT
  • go并发和并行
  • 一种解决SoC总线功能验证完备性的技术
  • Web3 与区块链:开启透明、安全的网络新时代
  • c#中Thread.Join()方法的经典示例
  • 深入了解越权漏洞:概念、危害与防范
  • MySQL 数据库编程-C++
  • dl学习笔记(9):pytorch数据处理的完整流程
  • wps中的vba开发
  • 力扣 LCR 078 合并K个升序链表
  • 【hive】记一次hiveserver内存溢出排查,线程池未正确关闭导致
  • React Native 开发 安卓项目构建工具Gradle的配置和使用
  • IntelliJ IDEA新版本的底部version control(或git)里local change窗口显示配置修改详细教程
  • MySQL三大日志——binlog、redoLog、undoLog详解
  • MCU应用踩坑笔记(ADC 中断 / 查询法)
  • 32.日常算法
  • 通过docker安装部署deepseek以及python实现
  • 批量提取word表格数据到一个excel
  • 使用 Axios 获取用户数据并渲染——个人信息设置
  • DeepSeek在FPGA/IC开发中的创新应用与未来潜力
  • 【GitLab CI/CD 实践】从 0 到 1 搭建高效自动化部署流程
  • 【DeepSeek-R1训练笔记】随手记录一些训练log