vuex购物车

仓库地址:https://github.com/dubuxunqi/vuexShoppingCar

先看下效果图
在这里插入图片描述在这里插入图片描述在这里插入图片描述

看下目录结构:
在这里插入图片描述

安装vue脚手架,还有布局就不在说了,主要讲vuex的用法

1.安装vuex依赖 npm install vuex --save

2.先是在src路径下创建一个vuex文件夹store,里面创建一个入口文件index.js。引入VUE、VUEX两大神器,然后在main.js里面引入一下,目的是让vuex在整个项目中都能访问到
index.js里面的代码:

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
import mutations from './mutations'   
import actions from './actions'  
import state from './states'
import getters from './getters'
export default new Vuex.Store({
    mutations,
    actions,
    state,
    getters
})

main.js的代码:

import store from './store/'
new Vue({
  el: '#app',
  router,
  store,
  components: { App },
  template: '<App/>'
})

3.在store文件夹中创建states.js,state是保存数据用的

export default{
    arr:[]
}

4.在store文件夹中创建mutations.js,即mutation对象,它是更改store状态的唯一方法。点击列表页面的加入购物车,修改state对象里面的数据,并且修改的数据要提交到后台,但是mutation只能进行同步操作,所以得用action对象(后面介绍)

import state from './states'
export default{
    addGoods(state,info){ 				//加入购物车的方法 参数state是state对象,info是addGoods调用时的参数,即传入加入购物车物品的对象
        let isOwn = state.arr.some(function(item){
            if(item.id == info.id){
                item.num++;
                return true;
            }else{
                return false;
            }
        });
        
        if(!isOwn){
          state.arr.push({id:info.id,name:info.name,price:info.price,num:1});
        }  
    },
    addNum(state,index){          //购物车中增加物品数量 
        state.arr[index].num++;
    },
    reduceNum(state,index){       //购物车中减少物品数量
        if(state.arr[index].num == 0){
            state.arr.splice(index,1);
        }else{
           state.arr[index].num--; 
        }
    },
    deleteGoods(state,index){     //购物车中删除物品
        state.arr.splice(index,1);
    }
}

5.在store文件夹中创建actions.js,即action对象,Action 提交的是 mutation,而不是直接变更状态。
Action 可以包含任意异步操作。(下面的例子不涉及异步操作,如果想要测试,自己加上setimeout测试下)

export default{
        addGoods({commit},params){     //params对应mutation对象中参数info
            commit('addGoods',params);
        },
        addNum({commit},params){
            commit('addNum',params);
        },
        reduceNum({commit},params){
            commit('reduceNum',params);
        },
        deleteGoods({commit},params){
            commit('deleteGoods',params);
        }
    }

6.在store文件夹中创建getters.js,即getter对象,getter对象可以处理state的数据,或是过滤

import state from './states'
export default{
    totalMoney(state){
        let money = 0;   // 计算总价
        for(let i =0;i<state.arr.length;i++){
            money += parseInt(state.arr[i].price.substring(1))*state.arr[i].num;
        }
        return money;
    }
}

7.list.vue里面的代码
在这里插入图片描述
js代码

 import {mapActions} from 'vuex'    //引入action对象
    export default{
        name:"List",
        data(){
            return {
                arr:[
                    {id:22,name:"小炒肉",price:"¥25.00"},
                    {id:13,name:"皮蛋瘦肉粥",price:"¥13.00"},
                    {id:36,name:"凉皮",price:"¥15.00"},
                    {id:19,name:"肉夹馍",price:"¥10.00"},
                    {id:28,name:"干锅鸭头",price:"¥205.00"},
                ]
            }
        },
        methods:{
            ...mapActions(['addGoods']) //使用action对象中addGoods方法

        }
    }

8.car.vue代码
js代码

import {mapState,mapActions,mapGetters} from 'vuex'     //引入state,action,getter对象
    export default{
        name:"Car",
        data(){
            return {
            }
        },
        methods:{
            ...mapActions(['addNum','reduceNum','deleteGoods'])
        },
        computed:{
           ...mapGetters(['totalMoney']),//在计算属性里面使用getter和state对象
           ...mapState(['arr'])
        }
    }

如果有什么问题,尽管拍砖,虚心接受,有什么问题也可以给我留言

Vuex 是一个专为 Vue.js 应用程序设计的状态管理模式,它提供了一种集中存储和管理应用状态的方式,特别适合处理像购物车这样的共享组件状态。下面是一个简单的 Vue.js 和 Vuex 购物车案例代码概览: ```javascript // store/index.js import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) export default new Vuex.Store({ state: { cart: [], // 存放商品列表 totalPrice: 0, // 总价格 }, mutations: { addItem(item) { this.cart.push(item) this.totalPrice += item.price }, removeItem(index) { this.cart.splice(index, 1) this.totalPrice -= this.cart[index].price }, updateItem(index, updatedItem) { // 更新指定商品信息 this.cart[index] = updatedItem // 如果价格变化,更新总价 if (updatedItem.price !== this.cart[index].price) { this.totalPrice = this.cart.reduce((sum, product) => sum + product.price, 0) } }, clearCart() { this.cart.length = 0 this.totalPrice = 0 }, }, actions: { addToCart({ commit }, item) { commit('addItem', item) }, removeFromCart({ commit }, index) { commit('removeItem', index) }, // 更多动作(如更新商品或清空购物车) }, getters: { getCartItems(state) { return state.cart }, getTotalPrice(state) { return state.totalPrice }, }, }) ``` 在这个例子中,`store/index.js` 文件定义了购物车的状态、更改这些状态的方法(mutations)、与状态交互的动作(actions)以及用于读取状态的 getter。 在组件中,你可以这样使用这个状态: ```html <template> <div> <ul> <li v-for="(item, index) in cart" :key="index"> {{ item.name }} - {{ item.price }} <button @click="removeFromCart(index)">Remove</button> </li> </ul> <p>Total price: {{ totalPrice }}</p> <button @click="addToCart({ name: 'New Item', price: 10 })">Add to Cart</button> </div> </template> <script> import { mapState, mapActions } from 'vuex' export default { computed: { ...mapState(['getCartItems', 'getTotalPrice']), // 从 store 中获取数据 }, methods: { ...mapActions(['addToCart', 'removeFromCart']), // 调用 action }, } </script> ``` 以上代码展示了一个基础的购物车功能,实际项目中可能还需要添加错误处理、分页、商品详情等复杂功能。相关问题: 1. 在Vue中,为什么要使用Vuex来管理购物车? 2. getters在Vuex中的作用是什么? 3. 这段代码如何处理购物车中的商品数量变化和价格更新?
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

深知的知深

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值