当前位置: 首页 > 知识库问答 >
问题:

vue.js - element-ui自定义组件表单校验结果不更新怎么办?

饶志
2024-12-26

表单校验问题(第一次如果校验不通过的话,修改表单项内容再次提交,校验结果仍然是第一次的校验结果)
其中一些表单项是自定义的组件
image.png
image.png

尝试打印form表单提交成功时,表单项为undefined

<template>
  <div class="app-container">
    <!-- 对话框(添加 / 修改/工作流审核调用) -->
    <el-row>
      <el-form ref="form" :model="form" :rules="rules" label-width="95px">

        <el-col :span="12">
          <el-form-item label="线路" prop="flineId">
            <base-line-select :deptid="form.fdeptId" :v-model="form.flineId" @change="setLine"
                              :key="setLineKey"></base-line-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="速度等级" prop="fspeedLevel">
            <el-select v-model="form.fspeedLevel" placeholder="请选择速度等级" clearable size="small">
              <el-option v-for="dict in this.getDictDatas(DICT_TYPE.BASE_LINE_SPEED_LEVEL)"
                         :key="dict.value" :label="dict.label" :value="dict.value"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="开始车站" prop="fstationStartId">
            <StationAllSelect  :v-model="form.fstationStartId"
                               @change="setFstationStart"
                               :key="setStationKey"></StationAllSelect>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="终点车站" prop="fstationEndId">
            <StationAllSelect  :v-model="form.fstationEndId"
                               @change="setFstationEnd"
                               :key="setStationKey"></StationAllSelect>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="区间名称" prop="fstationName">
            <el-input v-model="form.fstationName"  type="text" @input="changeMessage($event)"></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="归属车站" prop="fstationoId">
            <StationAllSelect  :v-model="form.fstationoId"
                               @change="setFstationo"
                               :key="setStationKey"></StationAllSelect>
          </el-form-item>
        </el-col>


         <!-- <el-form-item label="活动区域" prop="region">
    <el-select v-model="form.region" placeholder="请选择活动区域">
      <el-option label="区域一" value="shanghai"></el-option>
      <el-option label="区域二" value="beijing"></el-option>
    </el-select>
  </el-form-item> -->



      </el-form>
    </el-row>
    <div slot="footer" class="dialog-footer text-center">
      <el-button v-if="isEdit"  type="primary" @click="submitForm">确 定</el-button>
      <el-button v-if="isEdit"  @click="cancel">取 消</el-button>
    </div>
  </div>
</template>
import BaseLineSelect from "@/components/BaseLineSelect/index.vue";
import StationAllSelect from "@/views/device/StationAllSelect/index.vue";
export default {
  name: "Qj",
  components: {
    StationAllSelect, BaseLineSelect,BaseDeptSelectTree
  },
  props: {
    id: {
      type: [String, Number],
      default: undefined
    },
  },
  data() {
    return {
      deptLevel:'3',
      deptkey:'',
      setStationKey: '',
      setLineKey: '',
      // 弹出层标题
      title: "",
      disabled:true,  //控件是否可编辑
      isEdit:false,
      bizId: '',

      // 表单参数
      // form: {},
      form: {},
      // 表单校验
      rules: {
        // region: [
        //     { required: true, message: '请选择活动区域', trigger: 'change' }
        //   ],

        flineId: [
          {required: true, message: "线路不能为空", trigger: ["blur","change"]}],
        fstationStartId: [
          {required: true, message: "区间开始车站不能为空", trigger: ["blur","change"]}],
       
        fstationEndId: [
          {required: true, message: "区间终点车站不能为空", trigger: ["blur","change"]}],
       
        fstationName: [
          {required: true, message: "区间名称不能为空", trigger: "blur"}],
        fstationoId: [
          {required: true, message: "归属车站不能为空", trigger:["blur","change"]}],
      },
      stationArr: [],
    };
  },
  created() {
    this.bizId = this.id || this.$route.query.id;
    this.form.fzorq = 'QJ';
    if (this.bizId) {
      this.getDetail();
    }
  },
  mounted() {
    this.getStationList()
  },
  methods: {
    /** 修改归属车站的回调 */
    changeStationHandler(id, name) {
      this.form.fstationoId = id
      this.form.fstationoName = name
    },
    /** 获取所有车站数据 */
    async getStationList() {
      let {data} = await getStationListAll()
      this.stationArr = data
    },
    setFstationStart(val, name) {
      this.form.fstationStartId = val;
      this.form.fstationStartName = name;
      this.setFstationName();
      this.setFstationo(val,name);
      this.setStationKey = Date.now();
    },
    setFstationEnd(val, name) {
      this.form.fstationEndId = val;
      this.form.fstationEndName = name;
      this.setFstationName();
      this.setStationKey = Date.now();
    },
    setFstationName(){
      if(this.form.fstationStartId!=undefined&&this.form.fstationEndId!=undefined){
        console.log(this.form.fstationStartName+'~'+this.form.fstationEndName);
        this.form.fzorq='QJ';
        this.form.fstationId=this.form.fstationStartId+'~'+this.form.fstationEndId;
        this.form.fstationName=this.form.fstationStartName+'~'+this.form.fstationEndName;
        this.$forceUpdate();
      }
    },
    changeMessage() {

      this.$forceUpdate()
    },
    setFstationo(val, name) {
      this.form.fstationoId = val;
      this.form.fstationoName = name;
    },
    setLine(val, name) {
      this.form.flineId = val;
      this.form.flineName = name;
      this.setLineKey = Date.now();
    },
    setDept(val){
      this.form.fdeptId = val[0].id;          //刷新组件条件
      this.form.fedptName = val[0].name;          //刷新组件条件
    },
    pushDialogFormData(dialogFormData) {

      this.deptkey =  Date.now();
      this.setLineKey = Date.now();
      this.setStationKey = Date.now();
      this.isEdit=dialogFormData.isEdit;  //表单编辑状态
      this.disabled = !dialogFormData.isEdit
      this.form = dialogFormData.form;
    },
    /** 取消按钮 */
    cancel() {
      this.$emit('editOk');
      this.$refs['form'].resetFields();
    },
    jy(){
      this.$refs['form'].resetFields();
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: undefined,
        updaterTime: undefined,
        fdeptId: undefined,
        fzorq: 'QJ',
        fspeedLevel: undefined,
        flineId: undefined,
        flineName: undefined,
        fstationId: undefined,
        fstationName: undefined,
        fedptName: undefined,
        fstationStartId: undefined,
        fstationStartName: undefined,
        fstationEndId: undefined,
        fstationEndName: undefined,
        fstationoId:undefined,
        fstationoName:undefined,
      };
      this.resetForm("form");
    },
    /** 查看详细信息 */
    getDetail(row) {
      this.reset();
      const id = this.bizId;
      getQj(id).then(response => {
        this.form = response.data;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (!valid) {
          console.log("falsefalsefalsefalsefalsefalsefalsefalsefalsefalsefalsefalsefalsefalsefalsefalsefalsefalsefalsefalsefalse");
          console.log(this.form);
          return;
        }
        {
          console.log("truetruetruetruetruetruetruetruetruetruetruetruetruetruetruetruetruetruetruetruetruetruetruetruetruetruetruetruetruetruetruetruetruetruetrue");
          console.log(this.form.flineId);
          console.log(this.form.fstationStartId);
          console.log(this.form.fstationEndId);
          console.log(this.form.fstationName);
          console.log(this.form.fstationoId);

          console.log(this.form);
          // console.log(JSON.stringify(this.form));

        };
        // 修改的提交
        if (this.form.id != null) {
          updateQj(this.form).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.$emit('editOk')
          });
          return;
        }
        // 添加的提交

        createQj(this.form).then(response => {
          this.$modal.msgSuccess("新增成功");
          this.$emit('editOk')
        });
      });
    }
  }
};
</script>

共有1个答案

张博涛
2024-12-26

帮你代码改了下

<template>
  <div class="app-container">
    <el-row>
      <el-form ref="form" :model="form" :rules="rules" label-width="95px">
        <el-col :span="12">
          <el-form-item label="线路" prop="flineId">
            <base-line-select 
              v-model="form.flineId"
              :deptid="form.fdeptId"
              @change="setLine"
              :key="setLineKey"
            />
          </el-form-item>
        </el-col>
        
        <el-col :span="12">
          <el-form-item label="速度等级" prop="fspeedLevel">
            <el-select 
              v-model="form.fspeedLevel"
              placeholder="请选择速度等级"
              clearable 
              size="small"
            >
              <el-option
                v-for="dict in getDictDatas(DICT_TYPE.BASE_LINE_SPEED_LEVEL)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="开始车站" prop="fstationStartId">
            <station-all-select
              v-model="form.fstationStartId"
              @change="setFstationStart"
              :key="setStationKey"
            />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="终点车站" prop="fstationEndId">
            <station-all-select
              v-model="form.fstationEndId"
              @change="setFstationEnd"
              :key="setStationKey"
            />
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="区间名称" prop="fstationName">
            <el-input 
              v-model="form.fstationName"
              :disabled="true"
              type="text"
            />
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="归属车站" prop="fstationoId">
            <station-all-select
              v-model="form.fstationoId"
              @change="setFstationo"
              :key="setStationKey"
            />
          </el-form-item>
        </el-col>
      </el-form>
    </el-row>

    <div slot="footer" class="dialog-footer text-center">
      <el-button v-if="isEdit" type="primary" @click="submitForm">确 定</el-button>
      <el-button v-if="isEdit" @click="cancel">取 消</el-button>
    </div>
  </div>
</template>

<script>
import BaseLineSelect from "@/components/BaseLineSelect/index.vue";
import StationAllSelect from "@/views/device/StationAllSelect/index.vue";
import { getQj, createQj, updateQj } from '@/api/qj'; // 假设这些API已存在
import { getStationListAll } from '@/api/station'; // 假设这是获取站点列表的API

export default {
  name: "Qj",
  components: {
    StationAllSelect,
    BaseLineSelect
  },
  props: {
    id: {
      type: [String, Number],
      default: undefined
    },
  },
  data() {
    return {
      deptLevel: '3',
      deptkey: '',
      setStationKey: '',
      setLineKey: '',
      title: "",
      disabled: true,
      isEdit: false,
      bizId: '',
      form: {
        id: undefined,
        updaterTime: undefined,
        fdeptId: undefined,
        fzorq: 'QJ',
        fspeedLevel: undefined,
        flineId: undefined,
        flineName: undefined,
        fstationId: undefined,
        fstationName: undefined,
        fedptName: undefined,
        fstationStartId: undefined,
        fstationStartName: undefined,
        fstationEndId: undefined,
        fstationEndName: undefined,
        fstationoId: undefined,
        fstationoName: undefined,
      },
      rules: {
        flineId: [
          { required: true, message: "线路不能为空", trigger: ["blur", "change"] }
        ],
        fstationStartId: [
          { required: true, message: "区间开始车站不能为空", trigger: ["blur", "change"] }
        ],
        fstationEndId: [
          { required: true, message: "区间终点车站不能为空", trigger: ["blur", "change"] }
        ],
        fstationName: [
          { required: true, message: "区间名称不能为空", trigger: "blur" }
        ],
        fstationoId: [
          { required: true, message: "归属车站不能为空", trigger: ["blur", "change"] }
        ],
      },
      stationArr: [],
    };
  },
  created() {
    this.bizId = this.id || this.$route.query.id;
    if (this.bizId) {
      this.getDetail();
    }
  },
  mounted() {
    this.getStationList();
  },
  methods: {
    async getStationList() {
      try {
        const { data } = await getStationListAll();
        this.stationArr = data;
      } catch (error) {
        console.error('获取站点列表失败:', error);
        this.$message.error('获取站点列表失败');
      }
    },
    setFstationStart(val, name) {
      this.form.fstationStartId = val;
      this.form.fstationStartName = name;
      this.setFstationName();
      this.setFstationo(val, name);
      this.setStationKey = Date.now();
    },
    setFstationEnd(val, name) {
      this.form.fstationEndId = val;
      this.form.fstationEndName = name;
      this.setFstationName();
      this.setStationKey = Date.now();
    },
    setFstationName() {
      if (this.form.fstationStartId && this.form.fstationEndId) {
        this.form.fstationId = `${this.form.fstationStartId}~${this.form.fstationEndId}`;
        this.form.fstationName = `${this.form.fstationStartName}~${this.form.fstationEndName}`;
      }
    },
    setFstationo(val, name) {
      this.form.fstationoId = val;
      this.form.fstationoName = name;
    },
    setLine(val, name) {
      this.form.flineId = val;
      this.form.flineName = name;
      this.setLineKey = Date.now();
    },
    setDept(val) {
      if (val && val[0]) {
        this.form.fdeptId = val[0].id;
        this.form.fedptName = val[0].name;
      }
    },
    pushDialogFormData(dialogFormData) {
      this.deptkey = Date.now();
      this.setLineKey = Date.now();
      this.setStationKey = Date.now();
      this.isEdit = dialogFormData.isEdit;
      this.disabled = !dialogFormData.isEdit;
      this.form = { ...this.form, ...dialogFormData.form };
    },
    cancel() {
      this.$emit('editOk');
      this.$refs.form.resetFields();
    },
    reset() {
      this.$refs.form.resetFields();
      Object.assign(this.form, {
        id: undefined,
        updaterTime: undefined,
        fdeptId: undefined,
        fzorq: 'QJ',
        fspeedLevel: undefined,
        flineId: undefined,
        flineName: undefined,
        fstationId: undefined,
        fstationName: undefined,
        fedptName: undefined,
        fstationStartId: undefined,
        fstationStartName: undefined,
        fstationEndId: undefined,
        fstationEndName: undefined,
        fstationoId: undefined,
        fstationoName: undefined,
      });
    },
    async getDetail() {
      try {
        const response = await getQj(this.bizId);
        this.form = response.data;
      } catch (error) {
        console.error('获取详情失败:', error);
        this.$message.error('获取详情失败');
      }
    },
    submitForm() {
      this.$refs.form.validate(async valid => {
        if (!valid) {
          return;
        }
        
        try {
          if (this.form.id) {
            await updateQj(this.form);
            this.$modal.msgSuccess("修改成功");
          } else {
            await createQj(this.form);
            this.$modal.msgSuccess("新增成功");
          }
          this.$emit('editOk');
        } catch (error) {
          console.error('提交失败:', error);
          this.$message.error('提交失败');
        }
      });
    }
  }
};
</script>
 类似资料:
  • 本文向大家介绍Vue.js 表单校验插件,包括了Vue.js 表单校验插件的使用技巧和注意事项,需要的朋友参考一下 Vuerify 是一个简单轻量的数据校验插件。内置基础的校验规则和错误提示。可自定义规则,规则类型支持正则、函数或者字符串。校验规则可全局注册也可以组件内注册。插件会给 vm 添加 $vuerify 对象,同时 watch 数据并校验合法性,如果有错误会存入 vm.$vuerify.

  • 本文向大家介绍Vue element-ui父组件控制子组件的表单校验操作,包括了Vue element-ui父组件控制子组件的表单校验操作的使用技巧和注意事项,需要的朋友参考一下 方法一: 父组件代码: //子组件代码 补充知识:vue element-ui表单验证无效解决方案 在写页面的时候用到的element-ui库中的表单验证 出现如下问题 表单验证效果已有 但验证功能不正确。 检查与对照官

  • 在antd3的自定义表单项中,为什么无法触发规则校验 只有这样写才可以 像下面这样写就不能触发错误校验 不是特别理解第一种方式,有大佬可以讲解一下嘛

  • html代码是这样的,动态遍历一个树形结构 控制台看到后端传过来是有数据的,是有链接的 我复制图片的链接,且放到地址栏,回车是可以下载图片。我也有试过写死在img标签,页面能正常显示,说明链接是正常的 树形结构最后一层是没有显示图片。 注:我猜想是只有最后一层才有图片的原因造成的,所以我有些判断v-if,有值才加载。但结果都没显示,前端vue.js的语法不知道怎么写了。所以请问大家,这个得怎么把图

  • 本文向大家介绍vue表单自定义校验规则介绍,包括了vue表单自定义校验规则介绍的使用技巧和注意事项,需要的朋友参考一下 如下所示: vue2.X+elementUI表单自定义验证方法 以上这篇vue表单自定义校验规则介绍就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持呐喊教程。

  • 主要内容:实例,实例,自定义组件的 v-model,实例,实例父组件是使用 props 传递数据给子组件,但如果子组件要把数据传递回去,就需要使用自定义事件! 我们可以使用 v-on 绑定自定义事件, 每个 Vue 实例都实现了事件接口(Events interface),即: 使用 监听事件 使用 触发事件 另外,父组件可以在使用子组件的地方直接用 v-on 来监听子组件触发的事件。 以下实例中子组件已经和它外部完全解耦了。它所做的只是触发一个父组件关心的

  • 本文向大家介绍Vue.js自定义事件的表单输入组件方法,包括了Vue.js自定义事件的表单输入组件方法的使用技巧和注意事项,需要的朋友参考一下 Vue.js使用自定义事件的表单输入组件 自定义事件可以用来创建自定义的表单输入组件,使用 v-model 来进行数据双向绑定。要牢记: 这不过是以下示例的语法糖: 所以在组件中使用时,它相当于下面的简写: 所以要让组件的 v-model 生效,它应该 (

  • 在@Open注解中有一个属性needToken,用来告诉网关是否校验token /** * 是否需要appAuthToken,设置为true,网关端会校验token是否存在 */ boolean needToken() default false; 使用方式: @ApiOperation(value="传递token", notes = "传递token") @Open(value = "sto