Vue.js 简介
Vue.js 是一个渐进式 JavaScript 框架,用于构建用户界面。其核心库专注于视图层,易于与其他库或现有项目集成。Vue 的特点是轻量级、响应式数据绑定和组件化开发。
Vue 的核心特性
响应式数据绑定
Vue 通过数据劫持和发布-订阅模式实现响应式。数据变化时,视图自动更新。
组件系统
组件是 Vue 的核心概念,允许将 UI 拆分为独立可复用的模块。组件通过props接收数据,通过events通信。
指令系统
Vue 提供内置指令(如v-if、v-for、v-bind)扩展 HTML 功能,支持自定义指令。
单文件组件 (SFC)
通过.vue文件将模板、脚本和样式封装为一个单元,提升可维护性。
Vue 的基本用法
安装与初始化
通过 CDN 或 npm 安装:
npm install vue初始化 Vue 实例:
new Vue({ el: '#app', data: { message: 'Hello Vue!' } });模板语法
双大括号插值:
<div>{{ message }}</div>指令示例:
<div v-if="show">Visible</div> <ul> <li v-for="item in items">{{ item }}</li> </ul>计算属性与侦听器
计算属性缓存结果:
computed: { reversedMessage() { return this.message.split('').reverse().join(''); } }侦听器响应数据变化:
watch: { message(newVal, oldVal) { console.log('Message changed'); } }Vue 与 JavaScript 的联动
原生 JS 集成
Vue 实例可访问原生 JS 方法:
methods: { fetchData() { fetch('/api/data').then(response => response.json()); } }事件处理
通过v-on绑定事件:
<button v-on:click="handleClick">Click</button>方法定义:
methods: { handleClick() { alert('Clicked'); } }操作 DOM
使用ref直接访问 DOM:
<div ref="myDiv"></div>脚本中操作:
this.$refs.myDiv.style.color = 'red';Vue 与其他技术的联动
与后端 API 交互
通过axios发送请求:
axios.get('/api/users').then(response => { this.users = response.data; });状态管理(Vuex)
Vuex 是 Vue 的官方状态管理库:
const store = new Vuex.Store({ state: { count: 0 }, mutations: { increment(state) { state.count++; } } });组件中调用:
this.$store.commit('increment');路由(Vue Router)
配置路由:
const routes = [ { path: '/', component: Home }, { path: '/about', component: About } ]; const router = new VueRouter({ routes });导航示例:
<router-link to="/about">About</router-link>与 CSS 预处理器集成
在 SFC 中使用 Sass:
<style lang="scss"> .container { color: $primary; } </style>服务端渲染(Nuxt.js)
Nuxt.js 简化 SSR 配置:
// nuxt.config.js export default { modules: ['@nuxtjs/axios'] };高级用法
自定义指令
全局指令:
Vue.directive('focus', { inserted(el) { el.focus(); } });混入(Mixins)
复用逻辑:
const myMixin = { methods: { logMessage() { console.log(this.message); } } }; new Vue({ mixins: [myMixin] });插件开发
创建插件:
const MyPlugin = { install(Vue) { Vue.prototype.$myMethod = function() {}; } }; Vue.use(MyPlugin);性能优化
懒加载组件
动态导入组件:
const LazyComponent = () => import('./LazyComponent.vue');虚拟滚动
使用vue-virtual-scroller处理长列表:
<RecycleScroller :items="items" :item-size="50"> <template v-slot="{ item }">{{ item.name }}</template> </RecycleScroller>测试与调试
单元测试
使用Jest测试组件:
test('renders message', () => { const wrapper = mount(Component, { propsData: { message: 'Hello' } }); expect(wrapper.text()).toContain('Hello'); });Vue Devtools
浏览器扩展提供组件树、状态调试功能。
生态系统工具
- Vue CLI:项目脚手架。
- Vite:下一代前端工具链。
- Pinia:轻量级状态管理。
Vue与MySQL联动的基本架构
Vue作为前端框架无法直接连接MySQL数据库,需通过后端服务(如Node.js、PHP等)作为中介。典型架构为:Vue发起HTTP请求 → 后端API处理 → MySQL数据库操作 → 返回数据给Vue。
后端API创建(Node.js示例)
使用Express框架创建RESTful API:
const express = require('express'); const mysql = require('mysql2/promise'); const app = express(); app.use(express.json()); const pool = mysql.createPool({ host: 'localhost', user: 'root', password: 'yourpassword', database: 'test_db' }); // 查询接口 app.get('/api/users', async (req, res) => { const [rows] = await pool.query('SELECT * FROM users'); res.json(rows); }); // 插入接口 app.post('/api/users', async (req, res) => { const { name, email } = req.body; await pool.query('INSERT INTO users (name, email) VALUES (?, ?)', [name, email]); res.status(201).send(); }); app.listen(3000, () => console.log('API running on port 3000'));Vue前端实现数据请求
安装axios并配置基础请求:
// main.js import axios from 'axios'; axios.defaults.baseURL = 'http://localhost:3000'; Vue.prototype.$http = axios; // 组件中使用 export default { data() { return { users: [] } }, async created() { const res = await this.$http.get('/api/users'); this.users = res.data; }, methods: { async addUser() { await this.$http.post('/api/users', { name: 'New User', email: 'user@example.com' }); } } }数据库表结构示例
MySQL基础表结构:
CREATE TABLE users ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(50) NOT NULL, email VARCHAR(100) UNIQUE NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP );完整CRUD操作实现
更新与删除接口扩展:
// 后端更新接口 app.put('/api/users/:id', async (req, res) => { const { id } = req.params; const { name, email } = req.body; await pool.query('UPDATE users SET name=?, email=? WHERE id=?', [name, email, id]); res.status(204).send(); }); // 后端删除接口 app.delete('/api/users/:id', async (req, res) => { const { id } = req.params; await pool.query('DELETE FROM users WHERE id=?', [id]); res.status(204).send(); });Vue组件对应方法:
methods: { async updateUser(id) { await this.$http.put(`/api/users/${id}`, { name: 'Updated Name', email: 'updated@example.com' }); }, async deleteUser(id) { await this.$http.delete(`/api/users/${id}`); } }安全增强措施
实际项目需添加:
- JWT身份验证
- 输入参数验证
- SQL注入防护
- CORS配置
- 环境变量管理
错误处理优化
前后端统一错误处理:
// 后端错误中间件 app.use((err, req, res, next) => { console.error(err.stack); res.status(500).json({ error: 'Server error' }); }); // Vue全局拦截器 axios.interceptors.response.use( response => response, error => { alert(error.response?.data?.error || 'Request failed'); return Promise.reject(error); } );性能优化技巧
常用优化方案:
- 数据库连接池配置
- API响应缓存
- 分页查询实现
- 前端请求防抖
- 批量操作接口
项目结构建议
推荐分层架构:
project/ ├── client/ # Vue前端 │ ├── src/ │ └── ... ├── server/ # Node后端 │ ├── controllers/ │ ├── models/ │ └── ... └── database/ # SQL脚本Vue 与 Spring Boot 联动基础配置
前端 Vue 项目配置确保 Vue 项目已安装axios用于 HTTP 请求:
npm install axios在src/main.js中全局引入:
import axios from 'axios'; Vue.prototype.$http = axios;后端 Spring Boot 配置在pom.xml添加 Web 依赖:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>配置跨域支持(示例类):
@Configuration public class CorsConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("http://localhost:8080") // Vue 开发服务器地址 .allowedMethods("*"); } }数据交互实例
Spring Boot 控制器示例创建 RESTful 接口返回 JSON 数据:
@RestController @RequestMapping("/api") public class DemoController { @GetMapping("/message") public ResponseEntity<String> getMessage() { return ResponseEntity.ok("Hello from Spring Boot"); } }Vue 调用接口示例在 Vue 组件中发起请求:
export default { data() { return { responseData: '' } }, methods: { fetchData() { this.$http.get('http://localhost:8081/api/message') .then(response => { this.responseData = response.data; }) .catch(error => { console.error(error); }); } }, mounted() { this.fetchData(); } }表单提交与接收
Spring Boot 接收 POST 请求
@PostMapping("/submit") public ResponseEntity<String> handleSubmit(@RequestBody User user) { // 处理逻辑 return ResponseEntity.ok("Received: " + user.getName()); }Vue 表单提交
submitForm() { this.$http.post('http://localhost:8081/api/submit', { name: this.form.name, email: this.form.email }).then(response => { alert(response.data); }); }文件上传实现
Spring Boot 文件接收
@PostMapping("/upload") public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) { String fileName = file.getOriginalFilename(); // 保存文件逻辑 return ResponseEntity.ok("Uploaded: " + fileName); }Vue 文件上传组件
<input type="file" @change="handleFileUpload">handleFileUpload(event) { let file = event.target.files[0]; let formData = new FormData(); formData.append('file', file); this.$http.post('http://localhost:8081/api/upload', formData, { headers: { 'Content-Type': 'multipart/form-data' } }).then(response => { console.log(response.data); }); }异常处理方案
Spring Boot 全局异常处理
@ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(Exception.class) public ResponseEntity<String> handleException(Exception e) { return ResponseEntity.status(500).body(e.getMessage()); } }Vue 错误拦截在main.js中添加响应拦截:
axios.interceptors.response.use( response => response, error => { alert(`Error: ${error.response.data}`); return Promise.reject(error); } );生产环境部署建议
前端部署
- 执行
npm run build生成dist文件夹 - 将静态文件放置 Spring Boot 的
resources/static目录 - 或通过 Nginx 独立部署
后端优化
- 添加
spring-boot-starter-actuator监控 - 配置
application.properties中的服务端口:
server.port=8081 server.servlet.context-path=/api安全增强措施
JWT 认证集成Spring Boot 添加依赖:
<dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt</artifactId> <version>0.9.1</version> </dependency>Vue 请求头携带 token:
this.$http.get('/api/protected', { headers: { 'Authorization': `Bearer ${token}` } })实时通信方案
WebSocket 配置Spring Boot 启用 WebSocket:
@Configuration @EnableWebSocketMessageBroker public class WebSocketConfig implements WebSocketMessageBrokerConfigurer { @Override public void registerStompEndpoints(StompEndpointRegistry registry) { registry.addEndpoint("/ws").withSockJS(); } }Vue 使用sockjs-client:
import SockJS from 'sockjs-client'; let socket = new SockJS('http://localhost:8081/ws');