首页 > 解决方案 > Vuejs如何将一个项目从另一个数组添加到一个数组中?

问题描述

我正在制作产品页面和购物车页面,当我单击 Addtocart 按钮时,我希望将产品添加到购物车页面。现在我在没有数据库的情况下工作,所以我只想创建一个购物车数组,当我点击按钮时,数组会附加该产品

//this is product page
<template>
  <div class="container">
    //here i am listing the products
    <div v-for="product in products" :key="product.id">
      <div>
        <h1>{{ product.name }}</h1>
        //when i click this button i want to add the product the cart array, now to go to methods
        <button @click="Add" class="button" >Add to cart</button>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'Product',
  data () {
    return {
      products: [
        {name: 'product1', description: 'preview text', id: '1'},
        {name: 'prduct2', description: 'preview text 2', id: '2'}
      ],
      cart: []
  },
  methods: {
    //when i click the button here i have no idea how to add the product the cart
    Add () {
      this.$set(this.cart, 'name', 'product1')
    }
  }
}
</script>

标签: vue.js

解决方案


您可以期望Add函数中有一个参数,它是产品的 id。现在您可以在函数中获取此 id,然后获取与此 id 对应的产品并将其添加到cart数组中。


推荐阅读