繁体   English   中英

如何避免安装和更新 Vue 组件之间的重复

[英]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;
    }
  }
}

参考: vm.$watch - Vue 的官方 API

这个怎么样?

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.

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