首页 > 解决方案 > 从组件发出的 vuejs 降落在父组件的错误实例上

问题描述

我有一个现有组件,其中有一个付款方式设置表。这些可以通过模式弹出组件添加或编辑。我正在为每种付款方式添加一个可编辑的货币列表,其中包含一个表格和一个编辑器弹出窗口(本质上是在下一层重新创建相同的功能)

父组件实际上使用了 PaymentMethods 组件的两个不同实例——一个用于添加新的 PaymentMethod,另一个用于编辑现有的。这样做是因为它们通过它们的道具被赋予了不同的参数。

这里有一些伪代码来说明:

<button ... >New Payment Method</button> // triggers popup1
<payment-methods-modal id="popup1" ... > // for new items
<table ....>
<tr v-for="paymentMethods">
...
<td>
<button ...>Edit</button> // triggers popup2
</td>
<table>
<payment-methods-modal id="popup2"... > // for editing existing items

正如我在这里描述 的通过 UIKit 模式向数组添加元素在 vuejs 中不起作用

我在 PaymentMethodsModal 中添加了一个表格,以及一个打开新对话框“CurrenciesModal”的按钮。此对话框发出“onSave”事件。PaymentMethodsModal 通过添加/更新自己的货币数组来处理它(到目前为止只是添加,我还没有更新)

问题是,因为我有 2 个 PaymentMethodsModal 实例,所以 Vue 对哪个 PaymentMethodsModal 实例应该处理事件感到困惑。结果,除了一个处理程序调用之外的所有调用都在不正确的实例上触发 - 而不是我打开 CurrenciesModal 的那个实例。出于某种原因,它总是第二个。如果我输入项目“a”、“b”、“c”、“d”、“e”,CurrenciesModal 的正确实例将具有“b”,而另一个将具有“a”、“c”、“ d”、“e”。

当我发现时,我尝试了我能想到的唯一可能帮助 Vue 整理它的实例的方法——我给 PaymentMethodsModal 和 CurrenciesModal 的每个实例一个唯一的 id。它没有帮助。这是 Vue 中的错误,还是有什么可以做的?

我正在使用 Vue.js v2.6.10

编辑:根据流行的要求,这里是发出/处理事件的代码:

  1. PaymentMethodsModal:我的货币模式的标记:

    <payment-method-currency-modal key="a2" id="paymentMethodCurrencyPopup" :currency="newCurrency" @onSave="addCurrency" title="添加货币">

处理事件的方法:

addCurrency(cur) {
          if (!this.currencies) {
              console.log("currencies was undefined. creating.");
              this.currencies = [];
          }
          this.currencies.push(cur);
          this.newCurrency = { MinorUnitMultiplier: 100, Enabled: true };
          console.log(this.currencies);
      },
  1. CurrenciesModal - 发出事件:

    <button class="uk-button uk-button-primary uk-modal-close uk-border-rounded" type="button" @click="onSave" :disabled="!isValid()">

    方法: { onSave() { this.$emit("onSave", this.currency); },

标签: javascriptvue.js

解决方案


推荐阅读