[英]How to avoid duplication between mounting and updating a Vue component
在我正在开发的 Vue 应用程序中,我有许多表单组件,可用于创建新记录或修改现有记录。 在打开表单时,也可以单击另一条记录或单击创建,在这种情况下,表单的内容将分别被替换或清除。
我遇到的问题是我似乎无法避免我的data
功能和我的watch
功能之间的大量重复。
这是我的意思的一种简化示例:
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;
}
}
在安装表单时我必须做的所有事情都必须完成两次:一次在data
函数中设置初始反应属性,然后再次watch
任何可能更改的道具。 随着record
中的房产数量越来越多,这变得越来越难以管理并且容易出错。
有没有办法将这个设置逻辑保存在一个地方并避免这种重复?
要解决此问题,请向您的观察者添加一个immediate
属性,这也将使其在初始化时调用。 因此将处理您的record
属性的初始值。 看看下面的代码:
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;
}
}
}
这个怎么样?
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.