javascript - 如何将 for 循环中的当前项目传递给 vue.js 2 中的方法?

标签 javascript vuejs2

我正在 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/

相关文章:

javascript - 从 vue.js 中的嵌套数组过滤数据

javascript - Chrome 扩展程序与其余 Web 服务通信

javascript - 在 jQuery 中处理数据

javascript - 如何使用 Facebook 等单一输入验证电子邮件或电话号码

javascript - 在vuejs中使用mutation来过滤?

vuejs2 - Vuejs - 事件委托(delegate)和 v-for 上下文引用

javascript - 在 bootstrap-vue 选择选项中插入图像

javascript - html 表单验证 |所需的属性不再起作用 - 除了类型 ="email"- 怎么了?

Javascript + 浏览器 - 如何检测开发工具/firebug 何时打开?

node.js - 如何在vue应用中实现支付宝订阅?