首页 > 解决方案 > Vue:检查表单输入是否由用户更改

问题描述

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

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

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

感谢你们!

表单数据是这样的

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

标签: javascriptvue.js

解决方案


您可以通过拥有两个不同的对象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
 }
}

推荐阅读