php开源免费网站模板,网站开发的常用流程,企业网站访问量的第一来源是( ),com表示商业网站Vue.js 简介Vue.js 是一个渐进式 JavaScript 框架#xff0c;用于构建用户界面。其核心库专注于视图层#xff0c;易于与其他库或现有项目集成。Vue 的特点是轻量级、响应式数据绑定和组件化开发。Vue 的核心特性响应式数据绑定
Vue 通过数据劫持和发布-订阅模式实现响应式。…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-ifshowVisible/div ul li v-foritem 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:clickhandleClickClick/button方法定义methods: { handleClick() { alert(Clicked); } }操作 DOM使用ref直接访问 DOMdiv refmyDiv/div脚本中操作this.$refs.myDiv.style.color red;Vue 与其他技术的联动与后端 API 交互通过axios发送请求axios.get(/api/users).then(response { this.users response.data; });状态管理VuexVuex 是 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/aboutAbout/router-link与 CSS 预处理器集成在 SFC 中使用 Sassstyle langscss .container { color: $primary; } /style服务端渲染Nuxt.jsNuxt.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 :itemsitems :item-size50 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 APIconst 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: userexample.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: updatedexample.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 groupIdorg.springframework.boot/groupId artifactIdspring-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 ResponseEntityString 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 ResponseEntityString 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 ResponseEntityString uploadFile(RequestParam(file) MultipartFile file) { String fileName file.getOriginalFilename(); // 保存文件逻辑 return ResponseEntity.ok(Uploaded: fileName); }Vue 文件上传组件input typefile changehandleFileUploadhandleFileUpload(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 ResponseEntityString 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.port8081 server.servlet.context-path/api安全增强措施JWT 认证集成Spring Boot 添加依赖dependency groupIdio.jsonwebtoken/groupId artifactIdjjwt/artifactId version0.9.1/version /dependencyVue 请求头携带 tokenthis.$http.get(/api/protected, { headers: { Authorization: Bearer ${token} } })实时通信方案WebSocket 配置Spring Boot 启用 WebSocketConfiguration EnableWebSocketMessageBroker public class WebSocketConfig implements WebSocketMessageBrokerConfigurer { Override public void registerStompEndpoints(StompEndpointRegistry registry) { registry.addEndpoint(/ws).withSockJS(); } }Vue 使用sockjs-clientimport SockJS from sockjs-client; let socket new SockJS(http://localhost:8081/ws);