首页 > 解决方案 > js(vuejs)中函数内部的操作顺序

问题描述

我试图弄清楚在 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 =
    "";
}

标签: javascriptvue.jsvuejs2vue-component

解决方案


newContactfornumber中的数组addressemail与您稍后修改几行的数组相同。

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

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

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

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

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


推荐阅读