houzhongjian
2024-07-11 759b1c71011abd6b58c37d2566f3f3c208c2f1b2
提交 | 用户 | 时间
759b1c 1 <template>
H 2   <div class="app-container">
3     <el-form
4       ref="formRef"
5       :model="formData"
6       :rules="formRules"
7       label-width="100px"
8       v-loading="formLoading"
9     >
10       <el-form-item label="名字" prop="name">
11         <el-input v-model="formData.name" placeholder="请输入名字" />
12       </el-form-item>
13       <el-form-item label="班主任" prop="teacher">
14         <el-input v-model="formData.teacher" placeholder="请输入班主任" />
15       </el-form-item>
16     </el-form>
17   </div>
18 </template>
19
20 <script>
21 import * as Demo03StudentApi from '@/api/infra/demo03-inner';
22 export default {
23   name: "Demo03GradeForm",
24   components: {
25   },
26   props:[
27     'studentId'
28   ],// 学生编号(主表的关联字段)
29   data() {
30     return {
31       // 表单的加载中:1)修改时的数据加载;2)提交的按钮禁用
32       formLoading: false,
33       // 表单参数
34       formData: [],
35       // 表单校验
36       formRules: {
37         studentId: [{ required: true, message: "学生编号不能为空", trigger: "blur" }],
38         name: [{ required: true, message: "名字不能为空", trigger: "blur" }],
39         teacher: [{ required: true, message: "班主任不能为空", trigger: "blur" }],
40       },
41     };
42   },
43   watch:{/** 监听主表的关联字段的变化,加载对应的子表数据 */
44     studentId:{
45       handler(val) {
46         // 1. 重置表单
47         this.formData = {
48           id: undefined,
49           studentId: undefined,
50           name: undefined,
51           teacher: undefined,
52         }
53         // 2. val 非空,则加载数据
54         if (!val) {
55           return;
56         }
57         try {
58           this.formLoading = true;
59           // 这里还是需要获取一下 this 的不然取不到 formData
60           const that = this;
61           Demo03StudentApi.getDemo03GradeByStudentId(val).then(function (res){
62             const data = res.data;
63             if (!data) {
64               return
65             }
66             that.formData = data;
67           })
68         } finally {
69           this.formLoading = false;
70         }
71       },
72       immediate: true
73     }
74   },
75   methods: {
76     /** 表单校验 */
77     validate(){
78       return this.$refs["formRef"].validate();
79     },
80     /** 表单值 */
81     getData(){
82       return this.formData;
83     }
84   }
85 };
86 </script>