Vue:检查表单输入是否由用户更改

时间:2021-07-06 06:08:54

标签: javascript vue.js

我是 Vue 的新手,希望达到以下结果。

我有一个表单数据和一个保存按钮,在页面加载之前,它将获取数据库并填写表单数据。因为表单数据全部填满,保存按钮被禁用,用户无法点击,除非用户更改了一些数据,那么它知道表单数据发生了变化,保存按钮将不再被禁用,可以保存。

我知道应该使用 watch 属性,但实际上我该如何实现?

谢谢你们!

表单数据是这样的

data(){
  return {
     form: {
         firstName: "",
         lastName: ""
     }
  }
}

2 个答案:

答案 0 :(得分:0)

您可以通过拥有两个不同的对象 actualmodified 来执行以下操作。

<块引用>

这里我使用了underscore js进行deep clone或者isEqual,所以不要忘记导入。

computed: {
// Use is property for the save button to enable or disable
isDataChanged: function() {
    return _.isEqual(this.actualForm, this.modifiedForm);
 }
},
data() {
return {
    actualForm: {
        firstName: "",
       lastName: ""
    },
   modifiedForm: {
       firstName: "",
       lastName: ""
   }
 }
}, 
methods: {
fetchData: function() {
    // get data and assign it to actual form
    this.actualForm = responseData;
    this.modifiedForm = _.cloneDeep(this.actualForm) // this will create the new instance
 }
}

答案 1 :(得分:0)

您可以在下面这样的表格上使用手表。如果您需要查看表单中的嵌套属性,也可以使用 deep:true。

watch: {
    form: {
      deep: true,
      handler(val) {
        // Enable save button here. You can also evaluate any other condition to enable
      }
    }
  }

相关问题