我正在 vue.js 2 中构建(作为练习)购物车。我将我的商店商品和订单商品存储在我的 vue 数据数组中,并在 for 循环中为每个商店商品呈现一个按钮以添加商品订单(例如推送)。
这是在我的 vue 数据中存放我的商店数组中的项目列表的代码部分:
<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 元素:
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 */
}
}
})
如何将 for
循环中的项目传递给订单(例如:将其附加到 order.items)?
最佳答案
您只需将 item
作为参数传递给函数即可。
v-on:click="addItemToOrder(item)"
然后你就可以在你的Vue组件中使用它了
addItemToOrder: function(item){
this.order.items.push(item);
}
确保将 order.items
初始化为组件 data
中的空数组,以便您可以向其推送。
'order':{
'items': [],
'total': 0
},
一般来说,如果您知道数据将是什么,最好将数据初始化为正确的数据类型。
关于javascript - 如何将 for 循环中的当前项目传递给 vue.js 2 中的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42913031/