使用Vue做一个购物车
前言
最近我在做网上商城的一个项目,我负责购物车等模块,这是一个移动端项目。项目使用Vue全家桶开发。
本人最近在个人博客写一个小型的Vue实战文章,努力中,欢迎各位前往查看,指导点评!
正文
首先让我们看一下静态页面的效果图;
简单的说一下这个模块的需求:
- 勾选全选,所有商品全部选中,同时计算所选商品的总价和数量,反之取 消勾选。
- 勾选单个商品时,点击加减按钮,所属商品的数量会随之加减。当勾选全 部单选时,全选功能实现,反之亦然。
- 计算商品的总价和数量。
现在让我们开始吧
本文使用状态管理器(Vuex)接收后台数据!!!
const state = {
goodsList: [] //接收后台数据的数组
};
const getters = {
goodsList() {
return state.goodsList;
}
};
const mutations = {
setGoodsList(state, param) {
var needPush=true;
state.goodsList.forEach((item,index) => {
if (item.goodsId == param.goodsId) {
needPush=false;
//如果购物车里该商品已经有,更新该商品的数量到购物车列表里
item.num = parseInt(item.num) + parseInt(param.num);
}
});
if (needPush){
state.goodsList.push(param);
}
}
};
const actions = {
getGoodsList(context, param) {
context.commit("setGoodsList", param);
}
};
一:绑定加入购物车事件
1.组件的模板中 :
<div class="porp-buycart-btn">
<a href="javascript:void (0)" @click="joinList">加入进货单</a>
<a href="javascript:void (0)" @click="buyshop">立即购买</a>
</div>
- 组件的methods中 :
//加入购物车方法 dataList 后台数据 axios读取
buyshop(){
//异步提交
this.$store.dispatch("getGoodsList",this.dataList);
//成功后路由跳转
this.$router.push('/BaseMyOrder');
}
二:接收后台数据,存储Vuex当中,处理业务逻辑
见上文Vuex部分
三:恭喜伙伴们,做到这个程度购物车已经可以加入你的宝贝了。当然,还全选功能没有做。好,接下来我们继续讲全选功能。
//商品全选的方法 date 重后台读读取的数据做这里的参数 指商品是否被选中
//注意 data 在这里是我自定义的,并不是后台真正的字段
selectAll: function (data) {
if (!data) {
this.$store.state.goodsList.forEach(item => {
item.needChecked = true;
this.num = this.$store.state.goodsList.length;
});
} else {
this.$store.state.goodsList.forEach(item => {
item.needChecked = false;
this.num = 0;
});
}
}
四:商品单选功能,利用 v-model 这一指令判断是否已选中该商品
1.组件的模板中 :
<input type="checkbox" v-model="item.needChecked" class="group-check input-check checked_icon"
:class="{check_true:item.needChecked}" @click="select(item,index)">
- 组件的methods中 :
//商品单选的方法
select: function (item,index) {
item.needChecked = !item.needChecked;
//如果该商品选中时
if (item.needChecked == true) {
this.num++;
} else {
this.num--;
}
this.checked = []; //把选中后的标记(needChecked)push到这里
this.$store.state.goodsList.forEach(item => {
if (item.needChecked) {
this.checked.push(item.needChecked);
}
});
//利用push后的数组与数据库当中的数据进行长度对比
//判断是否是全选状态
if (this.checked.length === this.$store.state.goodsList.length) {
this.isSelectAll = true;
this.num = this.$store.state.goodsList.length;
} else {
this.isSelectAll = false;
this.num = 0;
}
},
五:计算所选中的商品总价和数量,computer计算属性刚好解决了这一需求
在组件的computer中 :
//定义一个总价的计算方法
totalCount: function () {
var count = 0; //声明总价格的变量
//遍历后台数据 foreach循环 es6 箭头函数在这里不再熬述
this.$store.state.goodsList.forEach((item, index) => {
//如果该商品已选中
if (item.needChecked) {
//计算总和
count += parseInt(item.num);
}
});
return count; //最后返回出去,以便后续引用该计算方法
}
至此,我们的需求就算是完成了。最后给大家留两个小问题思考一下
1.如何批量删除商品?
2.如果让我们加入后的商永久保存?tip:localStorage存储对象。
后文
本文的所有代码已经托管到GitHub,如果本文代码有误,
请以GitHub上的为准,GitHub地址:https://gitee.com/hellolgl/hoemdo.git