2017-03-20 11 views
2

私は、vue.jsにショッピングカートを構築しています(私は、私の店のアイテムと注文アイテムを私のvueデータ配列に格納しています、そして、各ショップアイテムのforループでレンダリングされたボタンは、注文(例:プッシュ)。私が合格するにはどうすればよいforループの現在の項目をvue.js 2のメソッドに渡すにはどうすればよいですか?

new Vue({ 
    el: '#my-order', 
    data:{ 
     'shop':[ 
      { 
       'title':'Website Content', 
       'description':"Order your Website content by the page. Our search-engine-optimized web content puts you ahead of the competition. 250 words.", 
       'price':25, 
       'sku':'web001' 
      }, 
      { 
       'title':'Blog Post', 
       'description':"We write blog posts that position your website as a go-to resource for expert knowlegde.", 
       'price':50, 
       'sku':'blog001' 
      }, 
      { 
       'title':'Twitter Post' 
      }, 
      { 
       'title':'Product Description' 
      } 
     ], 
     'customizations':null, 
     'order':{ 
      'items':null, 
      'total':null 
     }, 
     'customer':null, 
     'payment':null 
    }, 
    methods:{ 
     addItemToOrder: function(){ 
      /* Here is where I need to append the item to the cart */ 
     } 
    } 
}) 

:ここ

<fieldset> 
    <legend>Shop</legend> 
    <section v-if="shop"> 
     <article v-for="(item, index) in shop"> 
      <header><h1>{{ item.title }}</h1></header> 
      <p>{{ item.description }}</p> 
      <footer> 
       <ul> 
        <li>${{item.price}}</li> 
        <!-- find a way to set input name --> 
        <li><label>Quantity <input type="number" name=""></label></li> 
        <li><button v-on:click="addItemToOrder($event)">Add to Order</button></li> 
       </ul> 
      </footer> 
     </article> 
    </section> 
    <p v-else>No Items to Display</p> 
</fieldset> 

は私VUE要素である:ここで

は私VUEデータに私の店配列から項目の私のリストを収容するコードのセクションです forの注文をループします(例:order.itemsに追加)。

答えて

3

itemをパラメータとして関数に渡してください。

v-on:click="addItemToOrder(item)" 

次に、あなたがそれにプッシュできるようにVueのコンポーネント

addItemToOrder: function(item){ 
    this.order.items.push(item); 
} 

はあなたのコンポーネントdata内部の空の配列にorder.itemsを初期化していることを確認し、それを使用することができます。

'order':{ 
    'items': [], 
    'total': 0 
}, 

一般的に、データの種類がわかっている場合は、データを正しいデータ型に初期化することをお勧めします。

+0

動作しません。私は 'this.order.items.push( 'hello')'に文字列を直接渡してみても役に立たない。興味深いことに、 'alert( 'hello')'が動作します。 –

+0

'items'を' data'内の空の配列に初期化する必要があるため、動作しない可能性があります。あなたは何も「null」にプッシュすることはできません。私は私の答えを編集します。 –

関連する問題