Vue 表单编辑 没做更改 不让保存

1,378 阅读1分钟

需求:用户编辑表单的时候 如果没有做实际更改 就不让调保存接口

逻辑:点击编辑获取的表单数据, 与用户编辑后的表单数据进行比较, 如果一样就禁用保存按钮,否则走正常逻辑,需要监听表单。

实现:

  • 保存按钮默认可以点击
  • 监听比较 编辑前的表单和编辑后的表单 如果一样 保存按钮就不可以点击

因为表单是对象,比较2个对象,把他们转成字符串(这样也有问题 当2个对象的key 顺序不一样的时候),也可以用lodash _.equal方法,

stackoverflow.com/questions/2…

<template>
 <el-form>
   <el-col :span="24">
       <el-form-item label="响应名称" style="margin-top: 20px">
            <el-input
              v-model="ResponseList.name"
              :readonly="compileOne"
              clearable
              size="small"
            />
        </el-form-item>
     </el-col>
    <el-col :span="12">
      <el-form-item label="事件编号">
        <el-input
          v-model="ResponseList.businessNumber"
          readonly
          size="small"
        />
      </el-form-item>
    </el-col>
    <el-col :span="12">
      <el-form-item label="响应时间">
        <el-input
          size="small"
          v-model="ResponseList.createTime"
          readonly
        ></el-input>
      </el-form-item>
    </el-col>
  </el-form>
  <el-button
     v-if="isEditShow"
     type="primary"
     size="small"
     @click="edit">编辑</el-button>
  <el-button
    v-if="isSaveCancelShow"
    type="primary"
    size="small"
    @click="getSaveNull"
    :disabled="isFormSaveEnable"
    >保存</el-button>
</template>

data() {
  return {
   isFormSaveEnable: false, // 保存按钮默认是否禁用
   }
},
methods: {
 // 获取后台返回的表单值 
 getFormData(id).then((res) => {
        let obj = res.data
        
        // 考虑到后台返回的某些字段值是null 而表单原本没有值 
        // 用户输入然后清空 字段值从null 变成了''
        // 实际值没变化 
        Object.keys(obj).forEach(function(key) {
          if(obj[key] === null) {
            obj[key] = '';
            }
        })
        this.ResponseList = obj;
        // this.ResponseList.duty ??= '';
        this.formCopy = JSON.stringify(this.ResponseList);
 },
},
 watch: {
   // 监听表单 
   ResponseList: {
      handler() {
        if(JSON.stringify(this.ResponseList) === this.formCopy){
         this.isFormSaveEnable = true
        } else {
          this.isFormSaveEnable = false;
        }
      },
      // useful to watch deeply nested properties on a data variable
      deep: true,
    },
 }