场景:使用Vuex实现一个商品列表的添加、删除以及利用Vuex中的getters属性计算商品列表的总数总价格
添加商品时判断当前商品列表中是否包含了相同的商品
添加商品时,对添加表单做了校验
Vuex的使用及原理已经在上篇文章中介绍过了
vue2.x中使用vuex_前端-文龙刚的博客-CSDN博客
最终的效果:
开始实现
第一步:先布局页面
html
通过getters获取的商品价格是:{{ shopMoney }}通过getters获取的商品数量是:{{ shopCount }}添加商品 删除商品 css
.addShopTemp{display:flex;align-items:center;}.shopForm{float:left;}.shopForm .el-form-item{margin-bottom:0;}.shopCountMoney{padding:10px 0;}.shopCountMoney span{margin-right:10px;font-weight:600;}.shopCountMoney span:nth-child(1){color: brown;}.shopCountMoney span:nth-child(2){color: cornflowerblue;}
第二步:对表单做校验
shopRules:{shopName:[{ required: true, message: '请输入商品名称', trigger: 'blur' },],shopPrice:[{ required: true, message: '请输入商品单价', trigger: 'blur' },{ type: 'number', message: '商品单价必须为数字值'}],shopCount:[{ required: true, message: '请输入商品数量' },{ type: 'number', message: '商品数量必须为数字值'}]}
第三步:在组件页面中定义 添加 / 删除 方法
addShop(addShopData){//添加商品(做一个添加商品的表单,添加的时候,判断是否已经添加过)this.$refs.addShopFormRef.validate(valid => {if(valid){var idRandom = Math.random();//定义一个随机数,用来代替idlet shopItem={//定义一个对象,用作最终的数据提交id:idRandom,shopName:this.addShopData.shopName,shopPrice:this.addShopData.shopPrice,shopCount:this.addShopData.shopCount}// console.log('页面中添加的商品对象:',shopItem)this.$store.commit('addStoreShopItem',shopItem)//使用store中的方法添加商品this.$refs.addShopFormRef.resetFields()//清空表单}})},deleteShop(item){//删除商品this.$confirm('是否确定删除该商品?', '删除', {confirmButtonText: '确定',cancelButtonText: '取消',type: 'warning'}).then(() => {this.$store.commit('deleteShopItem',item)//调用vuex中的删除// this.$message({// type: 'success',// message: '删除成功!'// });}).catch(() => {this.$message({type: 'info',message: '已取消删除'}); });},
第四步:在Vuex中定义商品列表数据、添加 / 删除 的方法
state.js
shopCart:[//商品列表{id: 1,shopName: '苹果手机',shopPrice:6000,shopCount: 1},{id: 2,shopName: '华为手机',shopPrice: 5000,shopCount: 1},{id: 3,shopName: '小米手机',shopPrice: 4000,shopCount: 1}]
mutations.js
addStoreShopItem(state,obj){//添加商品方法// console.log('传递到store中的对象是:',obj)// console.log('store中的商品列表:',state.shopCart)const addType = state.shopCart.some((item)=>{//判断添加的id或名称跟已有的数组中的id或名称一样,并return结果if((obj.id == item.id) || (obj.shopName==item.shopName)){return true}else{return false}})if(!addType){//如果没有相同名称或id的话,就让添加state.shopCart.push(obj)}else{Message.error("不能添加相同名称的商品")return}},deleteShopItem(state,obj){//删除商品state.shopCart.some((item,index)=>{if(obj.id == item.id){state.shopCart.splice(index,1)Message.success("删除成功!!!")return true}})}
getters.js
shopMoney:(state)=>{//计算商品的总价格let total = 0state.shopCart.map(item=>{total+=item.shopCount*item.shopPrice})//或者这个方法:const total = state.shopCart.map(item => item.shopCount * item.shopPrice).reduce((a, b) => a + b, 0);return total},shopCount:(state)=>{//计算商品的总数let count = 0state.shopCart.map(item=>{count+=item.shopCount})return count}
好了,到这已经实现了商品列表的校验/添加/删除/统计功能 (#^.^#)
上一篇:/proc/cpuinfo详解