【问题标题】:How to avoid duplication between mounting and updating a Vue component如何避免安装和更新 Vue 组件之间的重复
【发布时间】:2018-07-18 13:27:57
【问题描述】:

在我正在开发的 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 中的属性数量越来越多,这变得越来越难以管理并且容易出错。

有没有办法将这个设置逻辑保存在一个地方并避免这种重复?

【问题讨论】:

    标签: javascript vue.js vue-component


    【解决方案1】:

    要解决此问题,请将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's Official API

    【讨论】:

    • 你的方法很好,但我接受了另一个答案,因为它还避免了复制所有数据属性的声明
    【解决方案2】:

    这个怎么样?

    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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-11
      • 1970-01-01
      • 2011-12-27
      • 2022-01-01
      • 2021-01-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多