我是Vue的新手,希望获得以下结果。
我有一个表单数据和一个保存按钮,在页面加载之前,它会提取数据库并填充表单数据。因为所有的表单数据都已填写,保存按钮被禁用,除非用户更改了某些数据,否则用户无法单击,然后它知道表单数据已经更改,保存按钮将不再被禁用,可以保存。
我知道应该使用watch属性,但实际上我该如何实现呢?
谢谢你们!
表单数据类似于此
data(){
return {
form: {
firstName: "",
lastName: ""
}
}
}
您可以通过拥有两个不同的对象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
}
}
您可以使用下面这样的监视窗体。如果您需要查看表单中的嵌套属性,也可以使用deep:true。
watch: {
form: {
deep: true,
handler(val) {
// Enable save button here. You can also evaluate any other condition to enable
}
}
}