简体   繁体   English

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

[英]Vue: Check form input is changed by user

I am new to Vue and want to achieve below result.我是 Vue 的新手,希望达到以下结果。

I have a form of data and a save button, before the page loads, it will fetch database and fill the form data.我有一个数据表单和一个保存按钮,在页面加载之前,它将获取数据库并填写表单数据。 Because all the form data are filled, the save button is disabled and the user can not click unless the user change some data, then it knows the form data has changed, the save button will no longer be disabled and can be saved.因为所有的表单数据都填满了,保存按钮被禁用,用户不能点击,除非用户更改了一些数据,那么它知道表单数据已经改变,保存按钮将不再被禁用,可以保存。

I know that should use watch property, but actually how I can implement this?我知道应该使用 watch 属性,但实际上我该如何实现呢?

Thank you guys!感谢你们!

The form data is like this表单数据是这样的

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

You can do something as below by having the two different objects actual and modified .您可以通过将两个不同的对象actualmodified

Here I have used underscore js for deep clone or isEqual, so don't forget to import.这里我使用了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
 }
}

You can use a watch on form like this below.你可以在下面这样的表格上使用手表。 You can also use deep:true if you need to watch nested property within form.如果您需要查看表单中的嵌套属性,也可以使用 deep:true。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM