完整代码见GitHub:
github.com/Veilhry/lanqiaoweb/tree/master/08
网页在线预览地址:
https://veilhry.github.io/lanqiaoweb/08/index.html
介绍
网上购物已经成为现代人生活中不可或缺的一部分,那么人们最常用到的购物车功能又是如何实现的呢?
本题需要在已提供的基础项目中,使用 Vue 2.x的知识,解决购物车商品管理过程中遇到的问题。
在浏览器中预览index.html页面,具体显示
当前出现的问题是:
·在“商品列表”中点击N次“加入购物车”按钮,会在购物车列表中出现N个该商品,且初始数量为1。
·在“购物车”中点击商品数据后的加号(“+”)按钮,会在购物车列表中重复出现该商品,且初始数量为1。
·在“购物车”中点击商品数据后的减号(“-”)按钮,并未将商品从购物车中移出。
目标
请在index.html文件中补全代码,最终实现购物车商品管理的功能。注意:请勿修改js/goods.js 文件中提供的数据!
具体需求如下:
(1)修改addToCart方法,实现将商品加入到购物车的功能。即:
1.点击“加入购物车”按钮后,如果购物车中不存在该商品,则将该商品添
加到购物车末尾,并初始化数量为1;
2.如果购物车中已存在该商品,则只在原数量上+1即可。
(2)完善removeGoods方法,实现移出购物车商品功能。即:
1.点击购物车商品后对应的减号(“-”)按钮,将其数量在原数量上-1;
2.如果减后数量为0,则将该商品从购物车中移除。
题解
主要考察vue2对js变量的监控来实现购物车功能,以及基础的事件绑定功能。值得注意的是vue2无法直接监控数组元素的改变,这是一个容易出错的地方。
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>购物车</title>
<script src="./js/goods.js"></script>
<script type="text/javascript" src="./js/vue.js"></script>
<link href="./css/index.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="app">
<!-- 商品列表 -->
<h3>商品列表</h3>
<ul id="goodsList">
<template v-for="goods in goodsList">
<li class="goods-item" :key="goods.id">
<div><img :src="goods.imgUrl" /> </div>
<div>{{goods.name}}</div>
<div>¥ {{goods.price}} </div>
<button @click="addToCart(goods)">加入购物车</button>
</li>
</template>
</ul>
<!-- 购物车 -->
<template v-if="cartList.length>0">
<h3>购物车</h3>
<ul id="cartList">
<template v-for="goods in cartList">
<li class="goods-item" :key="goods.id">
<div><img :src="goods.imgUrl" /> </div>
<div>{{goods.name}}</div>
<div>¥ {{goods.price}} </div>
<div class="item-control">
<button @click="removeGoods(goods)">-</button>
<h4>{{goods.num}}</h4>
<button @click="addToCart(goods)">+</button>
</div>
</li>
</template>
</ul>
</template>
</div>
</body>
</html>
<script>
var vm=new Vue({
el: '#app',
data: {
cartList: [],
goodsList: []
},
mounted() {
this.goodsList = GoodsArr;
},
methods: {
addToCart(goods) {
// TODO:修改当前函数,实现购物车加入商品需求
let flag = true
this.cartList.forEach(ele=>{
if (ele.name == goods.name)
{
flag = false
}
})
if (!goods.num | flag) {
goods.num = 1;
this.cartList.push(goods);
this.cartList = JSON.parse(JSON.stringify(this.cartList)); // vue2数组列表值修改无法直接监控,通过转义修改实现监控
}
else {
this.cartList.forEach(ele => {
if (ele.name == goods.name) {
ele.num++
}
});
}
},
removeGoods(goods) {
// TODO:补全代码实现需求
this.cartList.forEach((ele,inx) => {
if(ele.num==1){
this.cartList.splice(inx,1)
}
if (ele.name == goods.name) {
ele.num--
}
})
}
}
});
</script>