[英]How to avoid duplication between mounting and updating a Vue component
In a Vue application I'm working on I have a number of form components that can be used to either create a new record or amend an existing one.在我正在开发的 Vue 应用程序中,我有许多表单组件,可用于创建新记录或修改现有记录。 While a form is open, it is also possible to click another record or click create, in which case the contents of the form are replaced or cleared respectively.
在打开表单时,也可以单击另一条记录或单击创建,在这种情况下,表单的内容将分别被替换或清除。
The problem I have is that I can't seem to avoid a lot of duplication between my data
function and my watch
functions.我遇到的问题是我似乎无法避免我的
data
功能和我的watch
功能之间的大量重复。
Here's a simplified example of the kind of thing I mean:这是我的意思的一种简化示例:
props: ["record"],
data() {
return {
name: this.record ? this.record.name : "",
age: this.record ? this.record.age : null
};
},
watch: {
record(record) {
this.name = record ? record.name : "";
this.age = record ? record.age : null;
}
}
Everything I have to do to set up the form when it's mounted has to be done twice: once in the data
function to set up the initial reactive properties, and then again in watch
for any props that could change.在安装表单时我必须做的所有事情都必须完成两次:一次在
data
函数中设置初始反应属性,然后再次watch
任何可能更改的道具。 This gets more and more difficult to manage and mistake-prone as the number of properties in the record
gets bigger.随着
record
中的房产数量越来越多,这变得越来越难以管理并且容易出错。
Is there any way to keep this setup logic in one place and avoid this duplication?有没有办法将这个设置逻辑保存在一个地方并避免这种重复?
To resolve the problem add a immediate
property to your watcher which will make it call at initialization too.要解决此问题,请向您的观察者添加一个
immediate
属性,这也将使其在初始化时调用。 Therefore the initial value of your record
property will be handled.因此将处理您的
record
属性的初始值。 Take a look at the code below:看看下面的代码:
props: ["record"],
data() {
return {
name: "",
age: null
};
},
watch: {
record: {
immediate: true,
handler(value) {
this.name = this.record ? this.record.name : "";
this.age = this.record ? this.record.age : null;
}
}
}
Reference: vm.$watch - Vue's Official API参考: vm.$watch - Vue 的官方 API
How about this?这个怎么样?
props: ["record"],
data() {
return this.updateRecord(this.record, {});
},
watch: {
record(record) {
this.updateRecord(record, this);
}
},
updateRecord(what, where) {
where.name = what ? what.name : "";
where.age = what ? what.age : null;
return where;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.