上学期利用课余时间学习了Vue.js、Node.js,一直想作个完整的项目 实践 一下,但以前在学校并无那么多的时间。如今刚好有时间,就想着作一个项目巩固以前学到的东西。javascript
思来想去,最后决定模仿 小米商城 作一个电商项目,目前已经差很少作完了,本文就购物车模块的实现进行总结。css
完整项目代码仓库: https://github.com/hai-27/vue-store。项目部署在阿里云服务器,预览连接: http://106.15.179.105 (没有兼容移动端,请使用PC访问)。html
本文仅对前端部分进行总结,后端采用 Node.js(Koa)+Mysql 实现,详细代码请移步 https://github.com/hai-27/store-server。前端
新人发帖,如有不对的地方,请多多指教 ^_^vue
话很少说,先看效果java
页面使用了 element-ui 的Icon 图标
、 el-checkbox
、el-input-number
、el-popover
、el-button
,全部在main.js须要引入element-ui。ios
import ElementUI from 'element-ui'; import 'element-ui/lib/theme-chalk/index.css'; Vue.use(ElementUI);
页面代码以下:git
说明: 为了方便,此处直接放最终的代码。github
<template> <div class="shoppingCart"> <!-- 购物车头部 --> <div class="cart-header"> <div class="cart-header-content"> <p> <i class="el-icon-shopping-cart-full" style="color:#ff6700; font-weight: 600;"> </i> 个人购物车 </p> <span>舒适提示:产品是否购买成功,以最终下单为准哦,请尽快结算</span> </div> </div> <!-- 购物车头部END --> <!-- 购物车主要内容区 --> <div class="content" v-if="getShoppingCart.length>0"> <ul> <!-- 购物车表头 --> <li class="header"> <div class="pro-check"> <el-checkbox v-model="isAllCheck">全选</el-checkbox> </div> <div class="pro-img"></div> <div class="pro-name">商品名称</div> <div class="pro-price">单价</div> <div class="pro-num">数量</div> <div class="pro-total">小计</div> <div class="pro-action">操做</div> </li> <!-- 购物车表头END --> <!-- 购物车列表 --> <li class="product-list" v-for="(item,index) in getShoppingCart" :key="item.id"> <div class="pro-check"> <el-checkbox :value="item.check" @change="checkChange($event,index)"> </el-checkbox> </div> <div class="pro-img"> <router-link :to="{ path: '/goods/details', query: {productID:item.productID} }"> <img :src="$target + item.productImg" /> </router-link> </div> <div class="pro-name"> <router-link :to="{ path: '/goods/details', query: {productID:item.productID} }" >{{item.productName}}</router-link> </div> <div class="pro-price">{{item.price}}元</div> <div class="pro-num"> <el-input-number size="small" :value="item.num" @change="handleChange($event,index,item.productID)" :min="1" :max="item.maxNum" ></el-input-number> </div> <div class="pro-total pro-total-in">{{item.price*item.num}}元</div> <div class="pro-action"> <el-popover placement="right"> <p>肯定删除吗?</p> <div style="text-align: right; margin: 10px 0 0"> <el-button type="primary" size="mini" @click="deleteItem($event,item.id,item.productID)" >肯定</el-button> </div> <i class="el-icon-error" slot="reference" style="font-size: 18px;"></i> </el-popover> </div> </li> <!-- 购物车列表END --> </ul> <div style="height:20px;background-color: #f5f5f5"></div> <!-- 购物车底部导航条 --> <div class="cart-bar"> <div class="cart-bar-left"> <span> <router-link to="/goods">继续购物</router-link> </span> <span class="sep">|</span> <span class="cart-total"> 共 <span class="cart-total-num">{{getNum}}</span> 件商品,已选择 <span class="cart-total-num">{{getCheckNum}}</span> 件 </span> </div> <div class="cart-bar-right"> <span> <span class="total-price-title">合计:</span> <span class="total-price">{{getTotalPrice}}元</span> </span> <router-link :to="getCheckNum > 0 ? '/confirmOrder' : ''"> <div :class="getCheckNum > 0 ? 'btn-primary' : 'btn-primary-disabled'"> 去结算 </div> </router-link> </div> </div> <!-- 购物车底部导航条END --> </div> <!-- 购物车主要内容区END --> <!-- 购物车为空的时候显示的内容 --> <div v-else class="cart-empty"> <div class="empty"> <h2>您的购物车仍是空的!</h2> <p>快去购物吧!</p> </div> </div> <!-- 购物车为空的时候显示的内容END --> </div> </template>
/store/index.jssql
import Vue from 'vue' import Vuex from 'vuex' import shoppingCart from './modules/shoppingCart' Vue.use(Vuex) export default new Vuex.Store({ strict: true, modules: { shoppingCart } })
/store/modules/shoppingCart.js
export default { state: { shoppingCart: [] // shoppingCart结构 /* shoppingCart = { id: "", // 购物车id productID: "", // 商品id productName: "", // 商品名称 productImg: "", // 商品图片 price: "", // 商品价格 num: "", // 商品数量 maxNum: "", // 商品限购数量 check: false // 是否勾选 } */ } }
思路:
代码以下:
import { mapActions } from "vuex"; import { mapGetters } from "vuex"; computed: { ...mapGetters(["getUser", "getNum"]) }, methods: { ...mapActions(["setShoppingCart"]), } watch: { // 获取vuex的登陆状态 getUser: function(val) { if (val === "") { // 用户没有登陆 this.setShoppingCart([]); } else { // 用户已经登陆,获取该用户的购物车信息 this.$axios .post("/api/user/shoppingCart/getShoppingCart", { user_id: val.user_id }) .then(res => { if (res.data.code === "001") { // 001 为成功, 更新vuex购物车状态 this.setShoppingCart(res.data.shoppingCartData); } else { // 提示失败信息 this.notifyError(res.data.msg); } }) .catch(err => { return Promise.reject(err); }); } } }
vuex的mutations:
setShoppingCart (state, data) { // 设置购物车状态 state.shoppingCart = data; },
vuex的actions
setShoppingCart({ commit }, data) { commit('setShoppingCart', data); }
思路:
购物车html伪代码:
<div class="shoppingCart"> <div class="content" v-if="getShoppingCart.length>0"> <ul> <li class="header"> <!-- 购物车表头部分,省略详细代码 --> </li> <li class="product-list" v-for="(item,index) in getShoppingCart" :key="item.id"> <!-- 购物车列表部分,省略详细代码 --> </li> </ul> </div> <!-- 购物车为空的时候显示的内容 --> <div v-else class="cart-empty"> <div class="empty"> <h2>您的购物车仍是空的!</h2> <p>快去购物吧!</p> </div> </div> </div>
vuex的getters:
getShoppingCart(state) { // 获取购物车状态 return state.shoppingCart; }
思路:
html:
<el-button class="shop-cart" :disabled="dis" @click="addShoppingCart"> 加入购物车 </el-button>
逻辑代码以下:
methods: { ...mapActions(["unshiftShoppingCart", "addShoppingCartNum"]), // 加入购物车 addShoppingCart() { // 判断是否登陆,没有登陆则显示登陆组件 if (!this.$store.getters.getUser) { this.$store.dispatch("setShowLogin", true); return; } // 向后端发起请求,把商品信息插入数据库的购物车表 this.$axios .post("/api/user/shoppingCart/addShoppingCart", { user_id: this.$store.getters.getUser.user_id, product_id: this.productID }) .then(res => { switch (res.data.code) { case "001": // 新加入购物车成功 this.unshiftShoppingCart(res.data.shoppingCartData[0]); this.notifySucceed(res.data.msg); break; case "002": // 该商品已经在购物车,数量+1 this.addShoppingCartNum(this.productID); this.notifySucceed(res.data.msg); break; case "003": // 商品数量达到限购数量 this.dis = true; this.notifyError(res.data.msg); break; case "401": // 没有登陆 this.$store.dispatch("setShowLogin", true); this.notifyError(res.data.msg); break; default: this.notifyError(res.data.msg); } }) .catch(err => { return Promise.reject(err); }); } }
vuex的mutations:
unshiftShoppingCart(state, data) { // 添加商品到购物车 // 用于在商品详情页点击添加购物车,后台添加成功后,更新vuex状态 state.shoppingCart.unshift(data); }, addShoppingCartNum(state, productID) { // 增长购物车商品数量 // 用于在商品详情页点击添加购物车,后台返回002,“该商品已在购物车,数量 +1”,更新vuex的商品数量 for (let i = 0; i < state.shoppingCart.length; i++) { const temp = state.shoppingCart[i]; if (temp.productID == productID) { if (temp.num < temp.maxNum) { temp.num++; } } } }
vuex的actions:
unshiftShoppingCart({ commit }, data) { commit('unshiftShoppingCart', data); }, addShoppingCartNum({ commit }, productID) { commit('addShoppingCartNum', productID); }
思路:
html:
<div class="pro-action"> <el-popover placement="right"> <p>肯定删除吗?</p> <div style="text-align: right; margin: 10px 0 0"> <el-button type="primary" size="mini" @click="deleteItem($event,item.id,item.productID)">肯定</el-button> </div> <i class="el-icon-error" slot="reference" style="font-size: 18px;"></i> </el-popover> </div>
逻辑代码以下:
methods: { // 向后端发起删除购物车的数据库信息请求 deleteItem(e, id, productID) { this.$axios .post("/api/user/shoppingCart/deleteShoppingCart", { user_id: this.$store.getters.getUser.user_id, product_id: productID }) .then(res => { switch (res.data.code) { case "001": // 删除成功 // 更新vuex状态 this.deleteShoppingCart(id); // 提示删除成功信息 this.notifySucceed(res.data.msg); break; default: // 提示删除失败信息 this.notifyError(res.data.msg); } }) .catch(err => { return Promise.reject(err); }); } }
vuex的mutations:
deleteShoppingCart(state, id) { // 根据购物车id删除购物车商品 for (let i = 0; i < state.shoppingCart.length; i++) { const temp = state.shoppingCart[i]; if (temp.id == id) { state.shoppingCart.splice(i, 1); } } }
vuex的actions:
deleteShoppingCart({ commit }, id) { commit('deleteShoppingCart', id); }
思路:
el-input-number
实现。html:
<div class="pro-num"> <el-input-number size="small" :value="item.num" @change="handleChange($event,index,item.productID)" :min="1" :max="item.maxNum" > </el-input-number>
逻辑代码以下:
// 修改商品数量的时候调用该函数 handleChange(currentValue, key, productID) { // 当修改数量时,默认勾选 this.updateShoppingCart({ key: key, prop: "check", val: true }); // 向后端发起修改购物车商品数量的请求 this.$axios .post("/api/user/shoppingCart/updateShoppingCart", { user_id: this.$store.getters.getUser.user_id, product_id: productID, num: currentValue }) .then(res => { switch (res.data.code) { case "001": // 001表明修改为功 // 更新vuex状态 this.updateShoppingCart({ key: key, prop: "num", val: currentValue }); // 提示修改为功信息 this.notifySucceed(res.data.msg); break; default: // 提示修改失败信息 this.notifyError(res.data.msg); } }) .catch(err => { return Promise.reject(err); }); }
vuex的mutations:
updateShoppingCart(state, payload) { // 更新购物车 // 可更新商品数量和是否勾选 // 用于购物车点击勾选及加减商品数量 if (payload.prop == "num") { // 判断效果的商品数量是否大于限购数量或小于1 if (state.shoppingCart[payload.key].maxNum < payload.val) { return; } if (payload.val < 1) { return; } } // 根据商品在购物车的数组的索引和属性更改 state.shoppingCart[payload.key][payload.prop] = payload.val; }
vuex的actions:
updateShoppingCart({ commit }, payload) { commit('updateShoppingCart', payload); }
思路:
el-checkbox
实现,结算时提交所有勾选的商品。html:
<div class="pro-check"> <el-checkbox :value="item.check" @change="checkChange($event,index)"></el-checkbox> </div>
逻辑代码以下:
checkChange(val, key) { // 更新vuex中购物车商品是否勾选的状态 this.updateShoppingCart({ key: key, prop: "check", val: val }); }
说明: 此处使用的vuex的mutationsvuex和actions,和修改商品数量的是同一个,两个场景,经过传递的参数不一样进行区分。修改商品数量时传递参数是{ key: key, prop: "num", val: val },是否勾选商品传递的参数是{ key: key, prop: "check", val: val },请注意prop的变化。
思路:
html:
<div class="pro-check"> <el-checkbox v-model="isAllCheck">全选</el-checkbox> </div>
逻辑代码以下:
computed: { isAllCheck: { get() { return this.$store.getters.getIsAllCheck; }, set(val) { this.checkAll(val); } } }
vuex的getters:
getIsAllCheck(state) { // 判断是否全选 let isAllCheck = true; for (let i = 0; i < state.shoppingCart.length; i++) { const temp = state.shoppingCart[i]; // 只要有一个商品没有勾选当即return false; if (!temp.check) { isAllCheck = false; return isAllCheck; } } return isAllCheck; }
vuex的mutations:
checkAll(state, data) { // 点击全选按钮,更改每一个商品的勾选状态 for (let i = 0; i < state.shoppingCart.length; i++) { state.shoppingCart[i].check = data; } }
vuex的actions
checkAll({ commit }, data) { commit('checkAll', data); }
在购物车页面和根组件的顶部导航栏使用。
vuex的getters:
getNum(state) { // 购物车商品总数量 let totalNum = 0; for (let i = 0; i < state.shoppingCart.length; i++) { const temp = state.shoppingCart[i]; totalNum += temp.num; } return totalNum; }
在购物车页面和结算页面使用。
vuex的getters:
getCheckNum(state) { // 获取购物车勾选的商品总数量 let totalNum = 0; for (let i = 0; i < state.shoppingCart.length; i++) { const temp = state.shoppingCart[i]; if (temp.check) { totalNum += temp.num; } } return totalNum; }
在购物车页面和结算页面使用。
vuex的getters:
getTotalPrice(state) { // 购物车勾选的商品总价格 let totalPrice = 0; for (let i = 0; i < state.shoppingCart.length; i++) { const temp = state.shoppingCart[i]; if (temp.check) { totalPrice += temp.price * temp.num; } } return totalPrice; }
在结算页面使用。
vuex的getters:
getCheckGoods(state) { // 获取勾选的商品信息 // 用于确认订单页面 let checkGoods = []; for (let i = 0; i < state.shoppingCart.length; i++) { const temp = state.shoppingCart[i]; if (temp.check) { checkGoods.push(temp); } } return checkGoods; }
至此,购物车的前端部分已经所有实现:从数据库同步购物车数据,根据购物车数据动态生成购物车页面,添加商品到购物车,删除购物车中的商品,修改购物车商品的数量,是否勾选购物车商品,是否全选购物车商品, 计算购物车中商品的总数量,计算购物车中勾选的商品总数量,计算购物车中勾选的商品总价格,生成购物车中勾选的商品详细信息。
结束了,新人第一次发帖,如有不对的地方,请多多指教 ^_^本文是基于完整项目,就购物车模块的实现进行总结。
完整项目代码仓库:https://github.com/hai-27/vue-store。
项目预览连接: http://106.15.179.105 (没有兼容移动端,请使用PC访问)。
喜欢本文的同窗,不妨点个赞,若是能给完整项目代码仓库加个Star就更好了,谢谢 ^_^
对这个项目会作更多的总结,感兴趣的同窗能够点个关注。
感谢你的阅读!
做者 hai-27
2020年3月8日