-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerate_reports.py
More file actions
936 lines (898 loc) · 42.2 KB
/
Copy pathgenerate_reports.py
File metadata and controls
936 lines (898 loc) · 42.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
"""Generate two experiment reports from template, preserving code."""
import shutil
from docx import Document
from docx.shared import Pt
TEMPLATE = r"D:\xwechat_files\wxid_jcvp1npsjqgc22_61df\temp\RWTemp\2026-05\9e20f478899dc29eb19741386f9343c8\实验报告模板.docx"
OUT_DIR = "C:/Users/50469/python-learning/"
# ── Experiment 7: Vue3 待办事项应用 ───────────────────────────────────
EXP7_CODE = {
"name": "实验名称:实验七:Vue3 待办事项应用",
"seq": "实验序号:7",
"sections": [
("实验目的:", [
"掌握Vue3的组件化开发,掌握响应式、组件通信等技术。",
"开发一个具备添加、删除、修改、状态切换功能的待办事项管理应用,"
"并完成组件拆分与跨组件通信的实践。",
"使其能够适配不同尺寸的设备(手机、平板、桌面端),"
"保证在小屏设备上也有良好的显示和操作体验。",
]),
("二、实验步骤:", [
"1、实验准备",
"(1)创建Vue3项目:执行 npm create vue@latest vue3-todo-app 创建项目,安装依赖并启动开发服务器。",
"(2)服务器配置:在vite.config中配置端口8007、自动打开浏览器、路径别名@指向/src。",
"(3)目录结构:在src/components/下创建4个组件:TodoHeader.vue(头部添加)、TodoList.vue(列表容器)、TodoItem.vue(单个待办项)、TodoFooter.vue(底部统计)。",
"",
"2、App.vue(核心逻辑 + 全局状态管理)",
"",
"【App.vue 完整源码】",
"",
'<template>',
' <div class="app-container">',
' <TodoHeader />',
' <TodoList />',
' <TodoFooter />',
' </div>',
'</template>',
'',
'<script setup>',
"import { reactive, provide, watch } from 'vue'",
"import TodoHeader from '@/components/TodoHeader.vue'",
"import TodoList from '@/components/TodoList.vue'",
"import TodoFooter from '@/components/TodoFooter.vue'",
'',
'// 1. 定义响应式待办列表(初始数据)',
'const todoList = reactive([',
" { id: 1, text: '学习第1章 HTML 基础', done: false }",
'])',
'',
'// 2. 核心方法定义',
'const addTodo = (text) => {',
" if (!text.trim()) {",
" alert('待办内容不能为空!')",
' return',
' }',
' const newTodo = {',
' id: Date.now(),',
' text: text.trim(),',
' done: false',
' }',
' todoList.push(newTodo)',
'}',
'',
'const deleteTodo = (id) => {',
" if (window.confirm('确定要删除该待办吗?')) {",
' const index = todoList.findIndex(todo => todo.id === id)',
' if (index !== -1) {',
' todoList.splice(index, 1)',
' }',
' }',
'}',
'',
'const updateTodo = (id, newText) => {',
" if (!newText.trim()) {",
" alert('修改内容不能为空!')",
' return',
' }',
' const todo = todoList.find(todo => todo.id === id)',
' if (todo) {',
' todo.text = newText.trim()',
' }',
'}',
'',
'const toggleDone = (id) => {',
' const todo = todoList.find(todo => todo.id === id)',
' if (todo) {',
' todo.done = !todo.done',
' }',
'}',
'',
'// 3. 向子组件提供数据和方法',
"provide('todoList', todoList)",
"provide('addTodo', addTodo)",
"provide('deleteTodo', deleteTodo)",
"provide('updateTodo', updateTodo)",
"provide('toggleDone', toggleDone)",
'',
'// 4. 本地存储',
'const loadTodos = () => {',
" const savedTodos = localStorage.getItem('vue3-todo-list')",
' if (savedTodos) {',
' todoList.splice(0, todoList.length, ...JSON.parse(savedTodos))',
' }',
'}',
'const saveTodos = () => {',
" localStorage.setItem('vue3-todo-list', JSON.stringify(todoList))",
'}',
'loadTodos()',
'watch(todoList, saveTodos, { deep: true })',
'</script>',
'',
'<style scoped>',
'* { margin: 0 auto; padding: 0; }',
'.app-container {',
' max-width: 600px; width: 90%; margin: 0 auto;',
' padding: 20px; background-color: #f5f5f5;',
' border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);',
' min-height: 60vh; margin-top: 20px;',
'}',
'@media (max-width: 768px) {',
' .app-container { padding: 15px; margin-top: 10px; min-height: 70vh; }',
'}',
'@media (max-width: 480px) {',
' .app-container { width: 95%; padding: 10px;',
' border-radius: 4px; box-shadow: none; background-color: #fff; }',
'}',
'</style>',
"",
"3、TodoHeader.vue(添加待办组件)",
"",
"【TodoHeader.vue 完整源码】",
"",
'<template>',
' <div class="todo-header">',
' <input type="text" v-model="inputValue"',
' placeholder="请输入待办事项..." @keyup.enter="handleAdd">',
' <button @click="handleAdd">添加待办</button>',
' </div>',
'</template>',
'',
'<script setup>',
"import { ref, inject } from 'vue'",
"const addTodo = inject('addTodo')",
"const inputValue = ref('')",
'',
'const handleAdd = () => {',
' addTodo(inputValue.value)',
" inputValue.value = ''",
'}',
'</script>',
'',
'<style scoped>',
'.todo-header { display: flex; gap: 10px; margin-bottom: 20px; width: 100%; }',
'input { flex: 1; padding: 12px 15px; border: 1px solid #ddd;',
' border-radius: 4px; font-size: 16px; box-sizing: border-box; }',
'button { padding: 12px 20px; background-color: #42b983; color: white;',
' border: none; border-radius: 4px; cursor: pointer; font-size: 16px;',
' white-space: nowrap; }',
'button:hover { background-color: #359469; }',
'@media (max-width: 480px) {',
' .todo-header { flex-direction: column; gap: 8px; }',
' button { width: 100%; padding: 10px 0; }',
'}',
'</style>',
"",
"4、TodoItem.vue(单个待办项组件)",
"",
"【TodoItem.vue 完整源码】",
"",
'<template>',
' <div class="todo-item" :class="{ done: todo.done }">',
' <span v-if="!isEditing" class="todo-text">{{ todo.text }}</span>',
' <input v-else type="text" v-model="editText"',
' @keyup.enter="confirmEdit" @blur="confirmEdit"',
' ref="editInput" class="edit-input">',
' <div class="btn-group">',
' <button @click="toggleDone(todo.id)" class="btn-toggle">',
' {{ todo.done ? "取消" : "完成" }}',
' </button>',
' <button @click="startEdit" v-if="!isEditing && !todo.done"',
' class="btn-edit">修改</button>',
' <button @click="deleteTodo(todo.id)" class="btn-delete">删除</button>',
' </div>',
' </div>',
'</template>',
'',
'<script setup>',
"import { ref, inject, watch, onMounted } from 'vue'",
'const props = defineProps({',
' todo: { type: Object, required: true,',
' default: () => ({ id: "", text: "", done: false }) }',
'})',
"const deleteTodo = inject('deleteTodo')",
"const updateTodo = inject('updateTodo')",
"const toggleDone = inject('toggleDone')",
'const isEditing = ref(false)',
"const editText = ref('')",
'const editInput = ref(null)',
'',
'const startEdit = () => {',
' isEditing.value = true',
' editText.value = props.todo.text',
'}',
'const confirmEdit = () => {',
' updateTodo(props.todo.id, editText.value)',
' isEditing.value = false',
'}',
'onMounted(() => {',
' watch(isEditing, (newVal) => {',
' if (newVal && editInput.value) editInput.value.focus()',
' })',
'})',
'</script>',
'',
'<style scoped>',
'.todo-item { display: flex; justify-content: space-between;',
' align-items: center; padding: 12px 10px;',
' border-bottom: 1px solid #eee; margin-bottom: 8px;',
' flex-wrap: wrap; gap: 10px; }',
'.todo-text { flex: 1; font-size: 16px; word-break: break-all; }',
'.done { color: #999; text-decoration: line-through; }',
'.btn-group { display: flex; gap: 6px; }',
'.btn-group button { padding: 6px 10px; font-size: 14px;',
' border: none; border-radius: 4px; cursor: pointer; min-width: 60px; }',
'.btn-toggle { background-color: #2196f3; color: white; }',
'.btn-edit { background-color: #ff9800; color: white; }',
'.btn-delete { background-color: #f44336; color: white; }',
'.edit-input { flex: 1; padding: 6px; font-size: 16px; width: 100%;',
' box-sizing: border-box; }',
'@media (max-width: 480px) {',
' .todo-item { flex-direction: column; align-items: flex-start; padding: 10px 0; }',
' .btn-group { width: 100%; justify-content: flex-end; margin-top: 5px; }',
'}',
'</style>',
"",
"5、TodoList.vue(列表容器组件)",
"",
"【TodoList.vue 完整源码】",
"",
'<template>',
' <div class="todo-list">',
' <TodoItem v-for="todo in todoList"',
' :key="todo.id" :todo="todo" />',
' <div class="empty-tip" v-if="todoList.length === 0">',
" 暂无待办事项,添加你的第一个待办吧!",
' </div>',
' </div>',
'</template>',
'',
'<script setup>',
"import { inject } from 'vue'",
"import TodoItem from './TodoItem.vue'",
"const todoList = inject('todoList')",
'</script>',
'',
'<style scoped>',
'.todo-list { padding: 15px; background-color: white;',
' border-radius: 4px; margin-bottom: 20px;',
' width: 100%; box-sizing: border-box; }',
'.empty-tip { text-align: center; padding: 30px 20px;',
' color: #999; font-size: 16px; }',
'@media (max-width: 768px) {',
' .todo-list { padding: 10px; margin-bottom: 15px; }',
'}',
'</style>',
"",
"6、TodoFooter.vue(底部统计组件)",
"",
"【TodoFooter.vue 完整源码】",
"",
'<template>',
' <div class="todo-footer">',
' <span>待办:{{ pendingCount }} | 已完成:{{ completedCount }}</span>',
' </div>',
'</template>',
'',
'<script setup>',
"import { inject, computed } from 'vue'",
"const todoList = inject('todoList')",
'const pendingCount = computed(() => todoList.filter(t => !t.done).length)',
'const completedCount = computed(() => todoList.filter(t => t.done).length)',
'</script>',
'',
'<style scoped>',
'.todo-footer { padding: 15px 10px; text-align: center;',
' color: #666; font-size: 15px; width: 100%; box-sizing: border-box; }',
'@media (min-width: 992px) {',
' .todo-footer { position: sticky; bottom: 0; background-color: #f5f5f5; }',
'}',
'</style>',
"",
"7、响应式测试方法",
"(1)打开Chrome开发者工具(F12),切换到设备模拟模式(Ctrl+Shift+M)。",
"(2)选择不同设备(iPhone SE、iPhone 12、iPad等)查看页面布局是否自适应。",
"",
"8、功能测试与优化",
"(1)添加功能:输入内容点击添加按钮,列表新增项;输入空内容弹出提示。",
"(2)删除功能:点击删除按钮弹出确认提示,确认后项被移除。",
"(3)修改功能:点击修改按钮出现输入框(保留原内容),回车/失焦后更新。",
"(4)状态切换:点击完成按钮出现删除线,底部统计同步更新。",
"(5)项目打包:执行 npm run build 生成dist目录,可通过 npx serve dist 预览。",
]),
("三、实验结果:", [
"1、基础功能测试结果:",
" - 添加待办:输入内容后正常添加,空内容弹出「待办内容不能为空」提示,符合预期。",
" - 删除待办:点击删除弹出确认对话框,确认后移除,取消则不删除,符合预期。",
" - 修改待办:点击修改出现输入框保留原内容,修改后回车/失焦更新,空内容提示,符合预期。",
" - 状态切换:点击完成文本出现删除线,底部已完成数量+1,取消完成恢复,符合预期。",
"",
"2、响应式适配效果:",
" - 桌面端(>=992px):正常布局,app-container宽度90%,底部sticky固定。",
" - 手机端(<=768px):padding缩小,按钮和输入框字体略减。",
" - 超小屏(<=480px):头部垂直排列、按钮占满宽度、列表项垂直排列。",
"",
"3、数据持久化:localStorage保存待办数据,刷新后数据不丢失。",
"4、项目打包:npm run build成功生成dist目录。",
]),
("四、实验心得:", [
"1、本次实验基于Vue3的setup语法糖,通过reactive实现响应式数据管理,"
"利用provide/inject完成跨组件通信,拆分了4个功能组件实现职责分离。",
"2、核心功能包括待办事项的添加(非空验证)、删除(确认提示)、"
"修改(保留原内容)、状态切换,并通过计算属性实现底部数量统计。",
"3、通过CSS媒体查询和flex布局实现了三个断点的响应式适配"
"(768px/480px),掌握了移动端优先的响应式设计思路。",
"4、本地存储和项目打包拓展了应用的实用性,"
"理解了Vue项目从开发到部署的完整流程。",
]),
],
}
# ── Experiment 8: Vue3 响应式商城 ─────────────────────────────────────
EXP8_CODE = {
"name": "实验名称:实验八:Vue3 响应式商城",
"seq": "实验序号:8",
"sections": [
("实验目的:", [
"1、掌握基于Vue3核心技术(组合式API、响应式)的综合实战应用。",
"2、整合路由管理(Vue Router 4)、状态管理(Vuex 4)、"
"前后端交互(Axios)三大核心技术。",
"3、实现响应式商城首页和商品详情页,掌握页面无刷新跳转、"
"商品数据全局管理、前后端接口请求。",
"4、掌握响应式布局适配多端设备(PC/平板/手机)的实现方法。",
]),
("二、实验步骤:", [
"步骤1:项目基础配置",
"(1)创建Vue3项目:npm create vue@latest mall-app,安装依赖。",
"(2)安装核心依赖:npm install vue-router@4 vuex@next axios --save。",
"(3)配置vite.config:端口8008、跨域代理/api到https://portal-api.macrozheng.com、路径别名。",
"",
"【main.js 入口文件源码】",
"import { createApp } from 'vue'",
"import App from './App.vue'",
"import router from './router'",
"import store from './store'",
"import './assets/css/global.css'",
"import './assets/css/responsive.css'",
"",
"const app = createApp(App)",
"app.use(router)",
"app.use(store)",
"app.mount('#app')",
"",
"【App.vue 根组件源码】",
'<template>',
' <div class="app-container">',
' <Header />',
' <main class="main-content"><router-view></router-view></main>',
' <Footer />',
' </div>',
'</template>',
'',
'<script setup>',
"import Header from './components/common/Header.vue'",
"import Footer from './components/common/Footer.vue'",
'</script>',
'',
'<style scoped>',
'.app-container { width: 100%; min-height: 100vh;',
' display: flex; flex-direction: column; }',
'.main-content { flex: 1; width: 90%; max-width: 1200px;',
' margin: 0 auto; padding: 20px 0; }',
'</style>',
"",
"【global.css 全局样式源码】",
"* { margin: 0; padding: 0; box-sizing: border-box;",
' font-family: "Microsoft YaHei", sans-serif; }',
"a { text-decoration: none; color: #333; }",
"ul, li { list-style: none; }",
"img { display: block; width: 100%; object-fit: cover; }",
"button { border: none; outline: none; cursor: pointer;",
" background: #e64340; color: #fff; border-radius: 4px; }",
"",
"【responsive.css 响应式媒体查询源码】",
"/* 手机端(<=767px) */",
"@media (max-width: 767px) {",
" .goods-list { grid-template-columns: repeat(2, 1fr) !important; gap: 10px !important; }",
" .detail-container { flex-direction: column !important; }",
" .detail-content { flex-direction: column !important; }",
" .detail-img, .detail-info { width: 100% !important; }",
"}",
"/* 平板端(768px-991px) */",
"@media (min-width: 768px) and (max-width: 991px) {",
" .goods-list { grid-template-columns: repeat(3, 1fr) !important; }",
"}",
"/* PC端(>=992px) */",
"@media (min-width: 992px) {",
" .goods-list { grid-template-columns: repeat(4, 1fr) !important; }",
"}",
"",
"步骤2:Axios配置(前后端交互)",
"",
"【src/request/index.js Axios实例+拦截器源码】",
"import axios from 'axios'",
"",
"const http = axios.create({",
" baseURL: 'https://portal-api.macrozheng.com/',",
" timeout: 5000,",
" headers: { 'Content-Type': 'application/json;charset=utf-8' }",
"})",
"",
"// 请求拦截器:添加token",
"http.interceptors.request.use(",
" (config) => {",
" const token = sessionStorage.getItem('mall_token')",
" if (token) config.headers['Authorization'] = `Bearer ${token}`",
" return config",
" },",
" (error) => Promise.reject(error)",
")",
"",
"// 响应拦截器:统一处理数据",
"http.interceptors.response.use(",
" (response) => response.data,",
" (error) => {",
" if (error.response.status === 401) {",
" sessionStorage.removeItem('mall_token')",
" window.location.href = '/#/login'",
" }",
" return Promise.reject(error)",
" }",
")",
"export default http",
"",
"【src/request/api/goodsApi.js 商品接口封装源码】",
"import http from '../index'",
"",
"export const goodsApi = {",
" // 获取商品列表(GET)",
" getGoodsList: (params) => {",
" return http.request({",
" url: '/home/recommendProductList', method: 'get', params",
" })",
" },",
" // 获取商品详情(GET)",
" getGoodsDetail: (id) => {",
" return http.request({",
" url: `/product/detail/${id}`, method: 'get'",
" })",
" }",
"}",
"",
"步骤3:Vuex配置(商品状态管理)",
"",
"【src/store/modules/goods/states.js 状态源码】",
"export default {",
" goodsList: [],",
" goodsDetail: {},",
" loading: false",
"}",
"",
"【src/store/modules/goods/mutations.js 同步修改源码】",
"export default {",
" SET_GOODS_LIST: (state, list) => { state.goodsList = list },",
" SET_GOODS_DETAIL: (state, detail) => { state.goodsDetail = detail },",
" SET_LOADING: (state, status) => { state.loading = status }",
"}",
"",
"【src/store/modules/goods/getters.js 计算属性源码】",
"export default {",
" goodsTotal: (state) => state.goodsList.length,",
" hotGoods: (state) => state.goodsList.filter(item => item.sale > 500)",
"}",
"",
"【src/store/modules/goods/actions.js 异步操作源码】",
"import { goodsApi } from '@/request/api/goodsApi'",
"",
"export default {",
" async getGoodsList({ commit }, params) {",
" commit('SET_LOADING', true)",
" try {",
" const res = await goodsApi.getGoodsList(params)",
" if (res.code === 200) commit('SET_GOODS_LIST', res.data.product)",
" } catch (error) {",
" console.error('获取商品列表失败:', error)",
" } finally {",
" commit('SET_LOADING', false)",
" }",
" },",
" async getGoodsDetail({ commit }, id) {",
" commit('SET_LOADING', true)",
" try {",
" const res = await goodsApi.getGoodsDetail(id)",
" if (res.code === 200) commit('SET_GOODS_DETAIL', res.data)",
" } catch (error) {",
" console.error('获取商品详情失败:', error)",
" } finally {",
" commit('SET_LOADING', false)",
" }",
" }",
"}",
"",
"【src/store/modules/goods/index.js 模块入口源码】",
"import state from './states'",
"import mutations from './mutations'",
"import getters from './getters'",
"import actions from './actions'",
"",
"export default {",
" namespaced: true,",
" state, mutations, getters, actions",
"}",
"",
"【src/store/index.js Vuex根仓库源码】",
"import { createStore } from 'vuex'",
"import goods from './modules/goods'",
"const store = createStore({ modules: { goods } })",
"export default store",
"",
"步骤4:Vue Router配置(路由管理)",
"",
"【src/router/index.js 路由配置源码】",
"import { createRouter, createWebHistory } from 'vue-router'",
"",
"const routes = [",
" { path: '/', redirect: '/home' },",
" { path: '/home', name: 'Home',",
" component: () => import('@/views/Home.vue'),",
" meta: { title: 'Vue3商城 - 首页' } },",
" { path: '/detail/:id', name: 'Detail',",
" component: () => import('@/views/Detail.vue'),",
" meta: { title: 'Vue3商城 - 商品详情' } },",
" { path: '/:pathMatch(.*)*', name: 'NotFound',",
" component: () => import('@/views/NotFound.vue'),",
" meta: { title: '页面不存在' } }",
"]",
"",
"const router = createRouter({",
" history: createWebHistory(),",
" routes,",
" scrollBehavior() { return { top: 0 } }",
"})",
"router.afterEach((to) => {",
" if (to.meta.title) document.title = to.meta.title",
"})",
"export default router",
"",
"【NotFound.vue 404页面源码】",
'<template>',
' <div class="not-found">',
' <h2>404 - 页面不存在</h2>',
' <router-link to="/home" class="back-home">返回商城首页</router-link>',
' </div>',
'</template>',
'<style scoped>',
'.not-found { width: 100%; height: 100%; display: flex;',
' flex-direction: column; align-items: center;',
' justify-content: center; gap: 20px; }',
'.back-home { padding: 10px 20px; background: #e64340;',
' color: #fff; border-radius: 4px; }',
'</style>',
"",
"步骤5:公共组件开发",
"",
"【Header.vue 公共头部源码】",
'<template>',
' <header class="header">',
' <div class="header-container">',
' <h1 class="logo"><router-link to="/home">Vue3商城</router-link></h1>',
' <nav class="nav"><ul>',
' <li><router-link to="/home" class="nav-link">首页</router-link></li>',
' <li><a href="#" class="nav-link">热销商品</a></li>',
' <li><a href="#" class="nav-link">关于我们</a></li>',
' </ul></nav>',
' </div>',
' </header>',
'</template>',
'',
'<style scoped>',
'.header { width: 100%; background: #fff;',
' border-bottom: 1px solid #eee; padding: 10px 0;',
' position: sticky; top: 0; z-index: 999; }',
'.header-container { width: 90%; max-width: 1200px;',
' margin: 0 auto; display: flex;',
' justify-content: space-between; align-items: center; }',
'.logo a { font-size: 24px; font-weight: bold; color: #e64340; }',
'.nav ul { display: flex; gap: 30px; }',
'.nav-link { font-size: 16px; color: #333; transition: color 0.3s; }',
'.nav-link:hover { color: #e64340; }',
'@media (max-width: 767px) {',
' .header-container { flex-direction: column; gap: 10px; }',
'}',
'</style>',
"",
"【Footer.vue 公共底部源码】",
'<template>',
' <footer class="footer">',
' <div class="footer-container">',
" <p>(c) 2025 Vue3商城 版权所有 | 基于Vue3+Vue Router+Vuex+Axios开发</p>",
' </div>',
' </footer>',
'</template>',
'',
'<style scoped>',
'.footer { width: 100%; background: #333; color: #fff;',
' text-align: center; padding: 20px 0; margin-top: 30px; }',
'.footer-container { width: 90%; max-width: 1200px; margin: 0 auto; }',
'</style>',
"",
"【GoodsItem.vue 商品卡片组件源码】",
'<template>',
' <div class="goods-item" @click="toDetail(goods.id)">',
' <div class="goods-img"><img :src="goods.pic" alt="商品图片"></div>',
' <div class="goods-info">',
' <h3 class="goods-name">{{ goods.name }}</h3>',
' <div class="goods-price">¥{{ goods.price }}</div>',
' <div class="goods-sales">销量:{{ goods.sale }}+</div>',
' </div>',
' </div>',
'</template>',
'',
'<script setup>',
"import { useRouter } from 'vue-router'",
"const props = defineProps({",
" goods: { type: Object, required: true, default: () => ({}) }",
"})",
"const router = useRouter()",
"const toDetail = (id) => { router.push(`/detail/${id}`) }",
'</script>',
'',
'<style scoped>',
'.goods-item { border: 1px solid #eee; border-radius: 8px;',
' overflow: hidden; cursor: pointer; transition: box-shadow 0.3s; }',
'.goods-item:hover { box-shadow: 0 0 10px rgba(0,0,0,0.1); }',
'.goods-img { width: 100%; }',
'.goods-info { padding: 10px; display: flex;',
' flex-direction: column; gap: 8px; }',
'.goods-name { font-size: 16px; font-weight: 500;',
' white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }',
'.goods-price { font-size: 18px; color: #e64340; font-weight: bold; }',
'.goods-sales { font-size: 14px; color: #999; }',
'</style>',
"",
"步骤6:商城首页开发(src/views/Home.vue)",
"",
"【Home.vue 完整源码】",
"",
'<template>',
' <div class="home-container">',
' <div class="home-title">',
' <h2>商城首页</h2>',
" <p>商品总数:{{ goodsTotal }} | 热销商品:{{ hotGoods.length }}</p>",
' </div>',
' <div class="loading" v-if="loading">加载中...</div>',
' <div class="goods-list" v-else>',
' <GoodsItem v-for="goods in goodsList"',
' :key="goods.id" :goods="goods" />',
' </div>',
' <div class="no-goods" v-if="!loading && goodsList.length === 0">',
' 暂无商品数据~',
' </div>',
' </div>',
'</template>',
'',
'<script setup>',
"import { onMounted, computed } from 'vue'",
"import { useStore } from 'vuex'",
"import GoodsItem from '@/components/common/GoodsItem.vue'",
"",
"const store = useStore()",
"const goodsList = computed(() => store.state.goods.goodsList)",
"const loading = computed(() => store.state.goods.loading)",
"const goodsTotal = computed(() => store.getters['goods/goodsTotal'])",
"const hotGoods = computed(() => store.getters['goods/hotGoods'])",
"",
"onMounted(() => {",
" store.dispatch('goods/getGoodsList', { pageNum: 1, pageSize: 10 })",
"})",
'</script>',
'',
'<style scoped>',
'.home-title { margin-bottom: 20px; padding-bottom: 10px;',
' border-bottom: 1px solid #eee; }',
'.home-title h2 { font-size: 24px; color: #333; margin-bottom: 8px; }',
'.home-title p { font-size: 14px; color: #999; }',
'.loading, .no-goods { text-align: center; font-size: 18px;',
' padding: 50px 0; color: #666; }',
'.goods-list { display: grid; gap: 20px; width: 100%; }',
'</style>',
"",
"步骤7:商品详情页开发(src/views/Detail.vue)",
"",
"【Detail.vue 完整源码】",
"",
'<template>',
' <div class="detail-container">',
' <div class="loading" v-if="loading">加载中...</div>',
' <div class="detail-content"',
' v-else-if="Object.keys(goodsDetail).length > 0">',
' <div class="detail-img">',
' <img :src="goodsDetail.pic" alt="商品详情图">',
' </div>',
' <div class="detail-info">',
' <h2 class="detail-name">{{ goodsDetail.name }}</h2>',
' <div class="detail-price">',
' <span class="now-price">¥{{ goodsDetail.price }}</span>',
' <span class="ori-price">原价:¥{{ goodsDetail.originalPrice }}</span>',
' </div>',
' <div class="detail-count">',
' <span>销量:{{ goodsDetail.sale }}+</span>',
" <span>库存:{{ goodsDetail.stock }}件</span>",
' </div>',
' <div class="detail-desc">',
' <h3>商品描述:</h3>',
' <p>{{ goodsDetail.subTitle }}</p>',
' </div>',
' <div class="detail-btn">',
' <button class="buy-btn">立即购买</button>',
' <button class="cart-btn">加入购物车</button>',
' </div>',
' </div>',
' </div>',
' <div class="no-detail" v-else>暂无商品详情数据~</div>',
' </div>',
'</template>',
'',
'<script setup>',
"import { onMounted, computed } from 'vue'",
"import { useStore } from 'vuex'",
"import { useRoute } from 'vue-router'",
"",
"const store = useStore()",
"const route = useRoute()",
"const goodsDetail = computed(() => store.state.goods.goodsDetail)",
"const loading = computed(() => store.state.goods.loading)",
"",
"onMounted(() => {",
" const goodsId = route.params.id",
" store.dispatch('goods/getGoodsDetail', goodsId)",
"})",
'</script>',
'',
'<style scoped>',
'.detail-container { width: 100%; display: flex; gap: 30px;',
' align-items: flex-start; }',
'.detail-content { width: 100%; display: flex; }',
'.detail-img { width: 40%; border: 1px solid #eee;',
' border-radius: 8px; overflow: hidden; }',
'.detail-info { width: 60%; display: flex;',
' flex-direction: column; gap: 20px; }',
'.detail-name { font-size: 28px; color: #333; font-weight: bold; }',
'.detail-price { display: flex; gap: 20px; align-items: center; }',
'.now-price { font-size: 32px; color: #e64340; font-weight: bold; }',
'.ori-price { font-size: 16px; color: #999; text-decoration: line-through; }',
'.detail-count { display: flex; gap: 30px; font-size: 16px;',
' color: #666; padding-bottom: 10px;',
' border-bottom: 1px dashed #eee; }',
'.detail-desc h3 { font-size: 20px; margin-bottom: 10px; }',
'.detail-desc p { font-size: 16px; line-height: 1.8; color: #666; }',
'.detail-btn { display: flex; gap: 20px; margin-top: 20px; }',
'.detail-btn button { padding: 12px 30px; font-size: 18px; }',
'.cart-btn { background: #ff9900; }',
'</style>',
]),
("三、实验结果:", [
"1、路由功能测试:",
" - 首页点击商品卡片,无刷新跳转到商品详情页,URL携带商品id。",
" - 访问不存在路径跳转到404页面,可点击返回首页。",
" - 路由跳转后页面自动滚动到顶部。",
"",
"2、数据请求测试:",
" - 页面首次加载显示「加载中...」状态,数据返回后自动渲染。",
" - loading状态随请求开始/结束正确切换。",
" - 接口错误时控制台输出对应错误信息。",
"",
"3、Vuex状态管理测试:",
" - Vue Devtools中goods模块数据与页面渲染一致。",
" - goodsTotal和hotGoods getter正确计算。",
"",
"4、响应式布局测试:",
" - PC端(>=992px):商品列表4列网格,详情页左右分栏。",
" - 平板端(768px-991px):商品列表3列网格。",
" - 手机端(<=767px):商品列表2列网格,详情页上下分栏。",
]),
("四、实验心得:", [
"1、本次实验基于Vue3组合式API,整合了Vue Router 4、Vuex 4、"
"Axios三大核心技术,实现了响应式商城首页和商品详情页的开发。",
"2、掌握了Vue3项目的工程化目录结构,按功能模块拆分文件"
"(router/store/request/components/views)。",
"3、熟练运用Vue Router 4实现路由配置、懒加载、动态路由传参、"
"编程式导航和路由守卫,理解了单页应用的无刷新跳转原理。",
"4、掌握了Vuex 4的模块管理模式:组件dispatch Action -> "
"Action调用Axios -> commit Mutation -> 更新State -> 响应式渲染视图。",
"5、熟练运用Axios封装实例和拦截器,掌握了真实接口和模拟数据的两种方案。",
"6、掌握了响应式布局实现方法:Flex/Grid布局 + CSS媒体查询三断点。",
"7、理解了Vue3核心技术联动:Axios请求数据 -> Vuex管理数据 -> "
"Vue Router页面跳转 -> 组合式API渲染视图。",
]),
],
}
def set_cell_text(cell, text, font_size=Pt(14)):
"""Replace cell content with plain text, preserving font size."""
for p in cell.paragraphs:
for r in p.runs:
r.text = ""
first_para = cell.paragraphs[0]
first_para.clear()
run = first_para.add_run(text)
run.font.size = font_size
def write_section(cell, title, lines):
"""Add a section (title + lines) to the merged cell."""
from docx.oxml import OxmlElement
from docx.oxml.ns import qn
font_size = Pt(14)
# Section title (not code)
p = cell.add_paragraph()
r = p.add_run(title)
r.font.size = font_size
# Detect if a line looks like code
code_prefixes = ('<template>', '<template ', '</template>', '<script', '</script>',
'<style', '</style>', '<div', '</div>', '<header', '</header>',
'<footer', '</footer>', '<main', '</main>', '<nav', '</nav>',
'<h1', '<h2', '<h3', '<input', '<button', '<span', '<img',
'<router-link', '<router-view', '<p>', '<ul>', '<li>',
'import ', 'export ', 'const ', 'function ',
'let ', 'var ', 'return ', 'if ', 'else ',
'async ', 'await ', 'try ', 'catch ', 'finally ',
'new ', 'this.', 'typeof ', 'throw ',
'.header', '.todo', '.app-', '.goods', '.detail', '.home-',
'.footer', '.logo', '.nav-', '.btn-', '.not-found',
'.main-', '.loading', '.no-',
'@media', '* {', '}', '{ }')
for line in lines:
p = cell.add_paragraph()
r = p.add_run(line)
r.font.size = font_size
stripped = line.strip()
# Check if this line is code
is_code = False
if stripped:
if any(stripped.startswith(pref) for pref in code_prefixes):
is_code = True
elif stripped.startswith('//') or stripped.startswith('/*'):
is_code = True
if is_code:
_apply_code_formatting(p)
def _apply_code_formatting(paragraph):
"""Apply code block shading (F2F2F2) and border to a paragraph."""
from docx.oxml import OxmlElement
from docx.oxml.ns import qn
pPr = paragraph._element.get_or_add_pPr()
# Shading: fill=F2F2F2
shd = OxmlElement('w:shd')
shd.set(qn('w:val'), 'clear')
shd.set(qn('w:fill'), 'F2F2F2')
pPr.append(shd)
# Border: single-line on all 4 sides, sz=4
pBdr = OxmlElement('w:pBdr')
for side in ('top', 'left', 'bottom', 'right'):
border = OxmlElement(f'w:{side}')
border.set(qn('w:val'), 'single')
border.set(qn('w:sz'), '4')
border.set(qn('w:space'), '4' if side in ('left', 'right') else '1')
border.set(qn('w:color'), 'auto')
pBdr.append(border)
pPr.append(pBdr)
def clear_cell(cell):
"""Remove all paragraphs from a cell except keep one empty."""
paras = cell.paragraphs
for i in range(len(paras) - 1, 0, -1):
p = paras[i]
p._element.getparent().remove(p._element)
paras[0].clear()
def generate_report(exp_data, output_path):
"""Generate a report from template with experiment data."""
shutil.copy2(TEMPLATE, output_path)
doc = Document(output_path)
table = doc.tables[0]
set_cell_text(table.rows[2].cells[0], exp_data["name"])
set_cell_text(table.rows[2].cells[1], exp_data["seq"])
cell = table.rows[3].cells[0]
clear_cell(cell)
for title, lines in exp_data["sections"]:
write_section(cell, title, lines)
doc.save(output_path)
print(f" => Saved: {output_path}")
if __name__ == "__main__":
print("Generating Experiment 7 report...")
generate_report(EXP7_CODE, OUT_DIR + "实验七_Vue3待办事项应用_实验报告.docx")
print("Generating Experiment 8 report...")
generate_report(EXP8_CODE, OUT_DIR + "实验八_Vue3响应式商城_实验报告.docx")
print("Done!")