https://www.mzqy.online/cart/#/cart
app:(父组件)
<template>
<div class=”hello”>
<h1>购物车练习</h1>
<hr/>
<table>
<tr>
<td>名称:<input type=”text” v-model=”name”></td>
<td>价格:<input type=”text” v-model=”price”></td>
<td><button @click=”addProduct”>添加商品</button></td>
</tr>
</table>
<hr/>
<table>
<tr>
<td>名称</td>
<td>价格</td>
</tr>
<tr v-for=”(item,index) in ProductList” :key=”index”>
<td>{{item.name}}</td>
<td>{{item.price}}</td>
<td><button @click=”addCart(index)”>加入购物车</button></td>
</tr>
</table>
<hr/>
<cart :cartItem=”cartItem” @removeItem=”remove”></cart>
</div>
</template>
<script>
/* eslint-disable */
import Cart from ‘./cart.vue’
export default {
components: {
Cart
},
data () {
return {
name: ”,
price: 0,
ProductList: [
{
id: 0,
name: ‘物品111’,
price: 998
},
{
id: 1,
name: ‘物品222’,
price: 1998
}
],
cartItem: []
}
},
methods: {
remove (index) {
this.cartItem.splice(index, 1)
},
addProduct () {
this.ProductList.push({ name: this.name, price: this.price })
this.name = ”
this.price = 0
},
addCart (index) {
console.log(‘this.cartItem’)
const item = this.ProductList[index]
let isHas = this.cartItem.find(x => x.id == item.id)
if (isHas) {
isHas.number += 1
}else{
this.cartItem.push({
…item,
isActive: true,
number: 1
})
}
console.log(this.cartItem)
}
}
}
</script>
<style scoped>
</style>
cart:(子组件购物车)
<template>
<div>
<h1>购物车</h1>
<table>
<tr>
<td>勾选</td>
<td>名称</td>
<td>价格</td>
<td>数量</td>
</tr>
<tr v-for=”(item, index) in cartItem” :key=”index”>
<td><input type=”checkbox” v-model=”item.isActive”></td>
<td>{{item.name}}</td>
<td>{{item.price}}</td>
<td>
<span @click=”minus(index)”>-</span>
{{item.number}}
<span @click=”plus(index)”>+</span>
</td>
</tr>
<tr>
<td colspan=”2″>总价:{{allPrice}}</td>
</tr>
</table>
</div>
</template>
<script>
export default {
name: ‘Cart’,
props: [‘cartItem’],
methods: {
minus (index) {
if (this.cartItem[index].number === 1) {
console.log(this.$emit)
this.$emit(‘removeItem’, index)
} else {
this.cartItem[index].number -= 1
}
},
plus (index) {
this.cartItem[index].number += 1
}
},
computed: {
allPrice () {
var num = 0
this.cartItem.forEach(item => {
if (item.isActive) {
num += item.price * item.number
}
})
return num
}
}
}
</script>
<style>
</style>
http://slkjfdf.net/ – Aiwougd Asanoywav npw.irrh.mzqy.online.bqo.qh http://slkjfdf.net/
http://slkjfdf.net/ – Uciximi Owuseboci zld.qagw.mzqy.online.ozi.xx http://slkjfdf.net/