vue.js - 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>
解决方案
您可以期望Add
函数中有一个参数,它是产品的 id。现在您可以在函数中获取此 id,然后获取与此 id 对应的产品并将其添加到cart
数组中。
推荐阅读
- .net - 访问上次复制错误消息,就像它在 SSMS 的复制监视器视图中一样
- google-cloud-platform - 使用大查询流时如何监控加载到 BQ 表中的记录数?
- reactjs - 如何使用 antd 复选框在 reactjs 中获取多个复选框值?
- python - Pandas - 使用逻辑过滤 DataFrame
- php - 我需要比较 2 个模板,并需要从 html 中定义的变量中获取字符串与 PHP
- c# - 如何将原始数据列表转换为 Json 列表?
- java - 如何在 Mockito 中模拟注入的 bean?
- php - PHP - 为不存在的文章加载 404 页面而不更改 URL
- java - 0-1 和 4 之间的模式字符串匹配
- c# - 进度条的 Visibility 属性在运行时不变