当前位置: 首页 > news >正文

综合案例:使用vuex对购物车的商品数量和价格等公共数据进行状态管理

文章目录

        • 0.实现需求
        • 1.新建购物车模块cart
        • 2.使用json-server模拟向后端请求数据
        • 3.在vuex请求获取并存入数据,并映射到组件中,在组件中渲染【重点】
          • 3.1.安装axios
          • 3.2.准备actions和mutations,获取和存入数据到vuex中
          • 3.3.动态渲染:先用mapState映射list到组件页面
        • 4.点击修改数量并同步前后端【重点】
          • 4.1.要求和思路
          • 4.2.代码
        • 其他
          • 1.为什么在axios在项目中要局部安装

0.实现需求
  • 请求动态渲染购物车,数据存放在vuex中
  • 使用数字框修改数据
  • 动态计算总价和总数量

购物车的商品数量,商品价格以及下方的总价,总数量,是共用一个数据,
显然,此处可以用到vuex,这也是Vuex在Vue项目中常见的使用场景之一

1.新建购物车模块cart
  • step1:新建store/modules/cart.js
export default{namespaced:true,//state写成这种形式的原因和data一样:保证组件实例化后的数据独立state(){//上面就不要const state={}了,会报错return{list:[]}}
}
  • step2:挂载到vuex仓库上
import cart from "@/store/modules/cart"
const store = new Vue.Store({modules:{cart}
})

验证配置是否成功:控制台>vue>Root>cart>namespaced

2.使用json-server模拟向后端请求数据
  • 安装json-server
npm install json-server -g
  • 准备json数据

在vue根目录下创建db/db.json(数据可以让deepseek模拟)

{"cart": [{"id": 1,"name": "Wireless Keyboard","price": 49.99,"count": 2,"thumb":"https://img14.360buyimg.com/n7/jfs/t1/141271/22/14881/70446/5fb4a985E1cce213e/beb55f6d1d3221b5.jpg"},{"id": 2,"name": "Gaming Mouse","price": 59.99,"count": 1,"thumb":"https://img14.360buyimg.com/n7/jfs/t1/141271/22/14881/70446/5fb4a985E1cce213e/beb55f6d1d3221b5.jpg"},{"id": 3,"name": "External Hard Drive","price": 89.99,"count": 1,"thumb":"https://img14.360buyimg.com/n7/jfs/t1/141271/22/14881/70446/5fb4a985E1cce213e/beb55f6d1d3221b5.jpg"},{"id": 4,"name": "Bluetooth Speaker","price": 79.99,"count": 1,"thumb":"https://img14.360buyimg.com/n7/jfs/t1/141271/22/14881/70446/5fb4a985E1cce213e/beb55f6d1d3221b5.jpg"},{"id": 5,"name": "Smartphone Case","price": 19.99,"count": 3,"thumb":"https://img14.360buyimg.com/n7/jfs/t1/141271/22/14881/70446/5fb4a985E1cce213e/beb55f6d1d3221b5.jpg"},{"id": 6,"name": "Laptop Backpack","price": 39.99,"count": 1,"thumb":"https://img14.360buyimg.com/n7/jfs/t1/141271/22/14881/70446/5fb4a985E1cce213e/beb55f6d1d3221b5.jpg"},{"id": 7,"name": "USB Flash Drive","price": 14.99,"count": 5,"thumb":"https://img14.360buyimg.com/n7/jfs/t1/141271/22/14881/70446/5fb4a985E1cce213e/beb55f6d1d3221b5.jpg"},{"id": 8,"name": "Headphones","price": 69.99,"count": 1,"thumb":"https://img14.360buyimg.com/n7/jfs/t1/141271/22/14881/70446/5fb4a985E1cce213e/beb55f6d1d3221b5.jpg"},{"id": 9,"name": "Monitor Stand","price": 29.99,"count": 1,"thumb":"https://img14.360buyimg.com/n7/jfs/t1/141271/22/14881/70446/5fb4a985E1cce213e/beb55f6d1d3221b5.jpg"},{"id": 10,"name": "Desk Lamp","price": 24.99,"count": 1,"thumb":"https://img14.360buyimg.com/n7/jfs/t1/141271/22/14881/70446/5fb4a985E1cce213e/beb55f6d1d3221b5.jpg"}],"friends": [{"userID": 101,"name": "Alice Johnson","age": 28},{"userID": 102,"name": "Bob Smith","age": 34},{"userID": 103,"name": "Charlie Brown","age": 22}]
}
  • 启动
在db目录下打开CMD:
json-server db.json

踩坑:遇到了端口号被占用的报错

\db>json-server db.json
node:internal/errors:478ErrorCaptureStackTrace(err);^
RangeError [ERR_SOCKET_BAD_PORT]: options.port should be >= 0 and < 65536. 

解决方法:指定端口号:json-server db.json --port:3008
在这里插入图片描述

3.在vuex请求获取并存入数据,并映射到组件中,在组件中渲染【重点】
3.1.安装axios
全局安装:npm install axios -g
局部安装:npm installl axios --save

踩坑:错误地使用了全局安装,导致在package.json中找不到axios依赖,也就调用不成功

3.2.准备actions和mutations,获取和存入数据到vuex中

过程:actions使用axios发起异步get请求获取数据,提交,触发mutations中的函数,该函数更新state的状态,
即:让空数组list存放返回的数据(res.data)

state:{return{list:[]}
},
mutations:{updateList(state,newList){state.list=newList}
},
actions:{async getData(context){const res=await axios.get("http:localhost:3008/cart");console.log(res);//查看res的层级结构context.commit("updateList",res.data);//提交,触发mutations中的方法}
}//在页面中调用:App.vue
created(){//格式:$store.dispatch("模块名/xxx")this.$store.dispatch("cart/getData")
}
3.3.动态渲染:先用mapState映射list到组件页面
//App.vuecomputed: {...mapState("cart", ["list"]),}

此时list已经获取后台json文件中的cart数组中的数据作为其元素,并通过mapState映射到组件中,
因此组件可以直接使用list进行页面渲染

//父组件App.vue
//使用v-for取出商品列表,但不在父组件直接渲染,而是设置自定义属性item,通过父传子,在子组件中渲染<div class="app-container"><cart-header></cart-header><cart-item v-for="item in list" :key="item.id" :item="item"></cart-item><cart-footer></cart-footer></div>
//子组件CartItem.vue
//html<div class="wrapper goods-container"><!-- 左侧图片 --><div class="left"><img :src="item.thumb" alt="" class="avatar"></div><!-- 右侧商品描述 --><div class="right"><!-- 标题 --><div class="title">{{item.name}}</div><div class="info"><!-- 单价 --><div class="price">¥{{item.price}}</div><!-- 按钮区域 --><div class="btns"><button class="btn btn-light" @click="btnClick(-1)">-</button><span class="count">{{item.count}}</span><button class="btn btn-light" @click="btnClick(1)">+</button></div></div></div></div>//js
//通过props属性接收父组件传过来的参数itemprops: {item:{type:Object,required:true}}//css(****不重要****)
.goods-container {display: flex;
}.left {flex: 1;padding: 10px;text-align: center;
}.right {flex: 2;padding: 10px;box-sizing: border-box;
}
.title {font-size: 16px;font-weight: bold;color: #333;margin-bottom: 10px;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;
}
.price {font-size: 18px;color: #e4393c; /* 常见红色系表示优惠价 */margin-top: 5px;
}
.btns {margin-top: 15px;
}.btns button {display: inline-block;padding: 5px 10px;margin-right: 5px;font-size: 14px;cursor: pointer;border: none;border-radius: 3px;
}/* 不同类型的按钮样式 */
.btns .remove-btn {background-color: #ff4d4f;color: white;
}.btns .add-to-cart {background-color: #1abc9c;color: white;
}
4.点击修改数量并同步前后端【重点】
4.1.要求和思路

点击"+“和”-",实现数量的增减,要求不仅是vuex中的数据发生改变.后台json文件中也会同步修改
思路:

  • 按钮绑定点击事件,并传参,点击事件中会调用actions中的方法

  • actions中的方法主要做两件事:

    • 提交,触发mutations方法以更新vuex状态;
    • 使用axios.patch向后台发送请求,局部更新count属性
  • mutations中的方法根据匹配到的id,更新对应的count

4.2.代码
//CartItem.vue
//"+"和"-"按钮绑定btnClick
methods:{btnClick(num){const newCount=num+this.list.count;count newId=this.list.id//调用actions方法:updateCountAsyncthis.$store.dispatch("cart/updateCountAsync",{newId,newCount})}
}//cart.js
mutations:{updateList(state,obj){//通过传回来的id找到对应的商品goodsconst goods=state.list.find(item==>item.id===obj.id);//更新这件商品的数量goods.count=obj.count;}
},
actions:{async updateCountAsync(context,obj){//更新后端数据const res=await axios.patch(`http://localhost:3008/cart/${obj.newId}`,{count:obj.newCount})console.log(res.data)//更新前端数据context.commit("updateList",{id:obj.newId,count:obj.newCount})}
}
其他
1.为什么在axios在项目中要局部安装
1. 全局安装与局部安装的区别
当使用 npm install axios -g 进行全局安装时,Axios 被放置在系统的全局环境中,而不是当前项目的 node_modules 文件夹中。这意味着全局安装不会影响任何具体项目中的依赖列表,也不会更新该项目的 package.json 文件1。
因此,即使成功执行了 npm install axios -g,当前项目的 package.json 文件仍然不会有 axios 字段,这是预期行为而非错误。2. 导致模块未找到的根本原因
Vue 项目运行时,默认只会查找位于当前项目目录下的 node_modules 文件夹内的模块。如果 Axios 是通过 -g 参数全局安装的,则 Vue 构建工具(如 Webpack)无法识别该模块,从而引发 Module not found: Error: Can't resolve 'axios' 错误33. 正确的解决方案
为了使 Axios 在项目中可用,应将其作为局部依赖安装到当前项目中,而不是采用全局安装的方式。以下是具体的解决步骤:
方法一:局部安装 AXIOS 并保存到依赖项
执行以下命令将 Axios 安装为项目的局部依赖,并自动更新 package.json 文件:
npm install axios --save
此操作会在 package.json 的 dependencies 字段中添加 Axios 条目,同时下载对应的模块到 node_modules 文件夹中。对于像 Axios 这样的库,通常建议始终将其作为局部依赖安装。这样不仅可以确保不同项目间互不影响,还能更方便地管理版本冲突问题

相关文章:

  • GNOME扩展:ArcMenu的Brisk布局左右调换
  • C语言与指针3——基本数据类型
  • 大语言模型能力评定探讨
  • AI实现制作logo的网站添加可选颜色模板
  • 【OFDM过程中正交子载波特性的应用及全面解析】
  • FPGA:介绍几款高速ADC及其接口形式
  • 抽奖算法场景
  • Linux C++ JNI封装、打包成jar包供Java调用详细介绍
  • 第十六届蓝桥杯单片机组省赛(第一套)
  • 【HarmonyOS Next】地图使用详解(三)标点定位问题
  • 输入输出(python)
  • 【JavaScript-Day 1】从零开始:全面了解 JavaScript 是什么、为什么学以及它与 Java 的区别
  • 6.9.单源最短路径问题-BFS算法
  • (六——下)RestAPI 毛子(Http resilience/Refit/游标分页/异步大文件上传)
  • [英语单词] from under
  • 6.10.单源最短路径问题-Dijkstra算法
  • Linux系统常用命令、标准C库函数和系统调用
  • 27.电源和地的单点串并联接线隐患及对EMC的影响分析
  • 模型上下文协议(MCP)
  • HDLBIT-程序(Procedures)
  • “彩虹滑道”项目两男童相撞飞跌出去,景区:工作人员误判导致
  • 几天洗一次头发最好?终于有答案了...
  • 商务部新闻发言人就中美经贸对话磋商情况答记者问
  • 美“群聊泄密门”始作俑者沃尔兹将离职
  • 大学2025丨对话深大人工智能学院负责人李坚强:产学研生态比“造天才”更重要
  • 小核酸药物企业瑞博生物递表港交所,去年亏损2.81亿元