【问题标题】:Order of operations inside a function in js (vuejs)js(vuejs)中函数内部的操作顺序
【发布时间】:2020-07-19 17:52:09
【问题描述】:

我正在尝试在 vuejs 中创建一个联系人列表应用程序。一个联系人可以有多个地址、电子邮件和号码。所以我创建了输入和一个按钮,如果需要,可以添加另一个输入。

但是,在按下提交按钮后,我只想为每个单元(电子邮件、号码、地址)进行 1 个输入,并且想要清空其内容,但它会覆盖我返回的数据。我尝试做两个单独的功能,但没有帮助。

为了更好的理解,这里是图片

this.$emit 是我传递的数据。低于此值(绿色框内)的所有内容都会清除输入。

这里也是代码

onSubmit() {
  let numberValidation = this.numbers.map(el => el.value === "");
  let addressValidation = this.addresses.map(el => el.value === "");
  let emailsValidation = this.emails.map(el => el.value === "");

  let len =
    numberValidation.length +
    addressValidation.length +
    emailsValidation.length;

  for (let i = 0; i < len; i++) {
    if (
      numberValidation[i] === true ||
      addressValidation[i] === true ||
      emailsValidation[i] === true ||
      this.title.trim() === ""
    ) {
      return this.$alert("you have an empty space");
      break;
    }
  }
  const newContact = [
    {
      name: this.title,
      number: this.numbers,
      address: this.addresses,
      email: this.emails
    }
  ];

  this.$emit("newcontact", newContact);

  this.title = "";
  this.numbers.length = this.addresses.length = this.emails.length = 1;
  this.numbers[0].value = this.addresses[0].value = this.emails[0].value =
    "";
}

【问题讨论】:

    标签: javascript vue.js vuejs2 vue-component


    【解决方案1】:

    numberaddressemailnewContact 中的数组是相同的数组,您可以稍后修改几行。

    有多种方法可以解决此问题,但关键是使用不同的数组。

    在您的具体示例中,我可能会使用以下内容:

    this.numbers = [{ value: '' }];
    this.addresses = [{ value: '' }];
    this.emails = [{ value: '' }];
    

    请注意,这会将包含新对象的新数组分配给属性,它不会改变原始数组或其中的对象。

    从您的代码中不清楚对象是否具有其他属性,但如果它们只有 value,那么这就足够了。

    【讨论】:

      猜你喜欢
      • 2020-12-16
      • 2018-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-20
      • 1970-01-01
      • 2018-05-19
      • 2018-03-10
      相关资源
      最近更新 更多