【问题标题】:Vue: Check form input is changed by userVue:检查表单输入是否由用户更改
【发布时间】:2021-07-06 15:02:55
【问题描述】:

我是 Vue 新手,想达到以下结果。

我有一个数据表格和一个保存按钮,在页面加载之前,它会获取数据库并填写表格数据。因为所有的表单数据都填满了,保存按钮被禁用,用户不能点击,除非用户改变了一些数据,那么它就知道表单数据已经改变了,保存按钮将不再被禁用,可以保存。

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

谢谢你们!

表单数据是这样的

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

【问题讨论】:

  • 有 2 个模型,一个用于原始值,一个用于表单,然后在“可以保存”的计算属性中比较它们

标签: javascript vue.js


【解决方案1】:

您可以通过使用两个不同的对象actual 和modified 来执行以下操作。

这里我使用了下划线js进行深度克隆或者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
 }
}

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-02-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多