2017-02-14 114 views
0

我在vuejs中有一个v-for循环,它在每次迭代中显示一个组件。这是一个自动完成组件,当用户在输入框中键入内容时,该组件会搜索并显示产品名称。for循环中的Javascript vuejs组件

我在每个组件上都有一个@change="setProduct"属性,它可以在我的父组件中正确调用我的setProduct方法。

但我怎么知道哪个组件被更新了?传递给setProduct方法的所有内容是发出的产品的详细信息,但我不知道哪个组件发出该事件以知道要更新哪一行。


下面是一些相关的代码: 这是在父组件

<template> 
    <div class="row" v-for="line, i in invoice.InvoiceLines"> 
     <div class="col-xs-5"> 
      <auto-complete :list="productList" :value="line.Product.name" @change="setProduct"></auto-complete> 
     </div> 
     ... 
    </div> 
</template> 
<script> 
export default { 
    data() { 
     return { 
      invoice:{}, 
      productList:[] 
     }, 
    } 
    methods:{ 
     setProduct(product){ 
      //product has the details of the new product that was selected. But I don't know which invoice line it is referring to. 
     }, 
    } 
} 
</script> 

组件响应点击在下拉列表中选择一个用户,然后问题$发出(“变”,产品);

组件不知道父组件,所以它不知道它引用哪个发票行。我可以将索引传递给子组件,然后将其传回,但这似乎是vue的反模式。

也许有一个更简单的方法让我去做这件事?

感谢您的帮助。

+0

你应该能够在'setProduct'中传递一个产品或索引的id,或者通过其他方式来识别,你可以添加一些相关的代码给我们更多的想法。 – Saurabh

回答

0

由于您使用v-for,所以实际上你可以检索项的indexinvoice.InvoiceLines,你可以通过任何你想成为setProduct

<template> 
    <div class="row" v-for="(line, i) in invoice.InvoiceLines"> 
     <div class="col-xs-5"> 
      <auto-complete 
       :list="productList" 
       :value="line.Product.name" 
       @change="setProduct(line, i, $event)"></auto-complete> 
     </div> 
     ... 
    </div> 
</template> 

然后在JavaScript:

methods: { 
    setProduct(product, index, event){ 
     // product - the 'line' responsible in invoice.InvoiceLines 
     // index - the index of line in invoice.InvoiceLines 
     // event - the event object 
    }, 
}