vuex实现购物车

本文介绍了如何利用Vuex的状态管理库来实现购物车功能。首先讲解了获取接口数据food.json的过程,接着详细阐述了Vuex store的实现,包括index.js中的es6写法。然后,讨论了商品列表组件list.vue的实现,最后展示了购物车组件cart.vue的代码结构。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.接口数据:food.json

 [{
    "id": 11,
    "name": "鱼香肉丝",
    "price": 12
  }, {
    "id": 22,
    "name": "宫保鸡丁",
    "price": 14
  }, {
    "id": 34,
    "name": "土豆丝",
    "price": 10
  }, {
    "id": 47,
    "name": "米饭",
    "price": 2
  },{
    "id": 49,
    "name": "蚂蚁上树",
    "price": 13
  },
  {
    "id": 50,
    "name": "腊肉炒蒜薹",
    "price": 15
  }]

2.store数据:index.js

import Vue from "vue";
import Vuex from 'vuex';
import axios from 'axios';

Vue.use(Vuex);
const state = {
  shop_list:[],
  add:[],
  count:0
}
const getters ={
	count(state){
		return state.count;
	},
	//1-1.获取商品列表
	// getShopList:state => state.shop_list,
	getShopList(state){
		return state.shop_list
	},
	//1-2.获取购物车列表
	addShopList(state){
		return state.add;
	},
	//1-3.获取总数量
	totalNum:(state,getters) =>{
	  let total =0;
	  getters.addShopList.map(n=>{
	    total += n.num;
	  })
	  return total;
	},
	//1-4.计算总价格
	totalPrice:(state,getters)=>{
	  let total=0;
	  getters.addShopList.map(n=>{
	    total += n.num*n.price
	  })
	  return total;
	}
}
const actions={
   add({commit},n){
		commit('add',n);
	},
  //2-1.加入购物车
  addToCart({commit},product){
    commit('addCart',product)
  },
  //2-2.清空购物车
  clearToCart({commit}){
    commit('clearCart')
  },
  //2-3.删除单个物品
  deletToShop({commit},product){
    commit('deletShop',product)
  },
  getFood(context){
	 axios.get('../../static/food.json').then(res => { 
          context.commit('getFood', res.data)  // 通过接口获取的后台数据保存到store中,等待组件取用
	 })
  }
}
const mutations ={
	//参数的使用
	add(state,n){
		state.count+=n;
		return state.count;
	},
   //3-1加入购物车
  addCart(state,product){
		//查看过购物车中对应的商品
    let record = state.add.find(n => n.id == product.id);
		//如果从未加入过购物车,就在购物车中添加该商品,并增加商品数量
    if(!record){
      state.add.push({
        id:product.id,
		name:product.name,
		price:product.price,
        num:1
      })
    }else{//如果加入了购物车,则改变商品数量
      record.num++;
    }
  },
   //3-2清空购物车
   clearCart(state){
     state.add=[];
   },
   //3-3删除单个物品
   deletShop(state,product){
     state.add.forEach((item,i)=>{
       if(item.id == product.id){
         state.add.splice(i,1)
       }
     })
   },
   getFood(state, obj){
	   state.shop_list = obj;
   }
}

export default new Vuex.Store({
  state,getters,actions,mutations
})

index.js
es6写法

import Vue from "vue";
import Vuex from 'vuex';
Vue.use(Vuex);
const state = {
  shop_list: [{
    id: 11,
    name: '鱼香肉丝',
    price: 12,
  }, {
    id: 22,
    name: '宫保鸡丁',
    price: 14
  }, {
    id: 34,
    name: '土豆丝',
    price: 10
  }, {
    id: 47,
    name: '米饭',
    price: 2
  },{
    id: 49,
    name: '蚂蚁上树',
    price: 13
  },
  {
    id: 50,
    name: '腊肉炒蒜薹',
    price: 15
  }],
  add:[]
}
const getters ={
	
  //获取商品列表
  getShopList:state => state.shop_list,
  //获取购物车列表 map,find,...对象
  addShopList:state => {
    return state.add.map(({id,num})=>{
      let product = state.shop_list.find(n => n.id == id);
      if(product){
        return{
          ...product,
          num
        }
      }
    })
  },
	 
  //获取总数量
  totalNum:(state,getters) =>{
    let total =0;
    getters.addShopList.map(n=>{
      total += n.num;
    })
    return total;
  },
  //计算总价格
  totalPrice:(state,getters)=>{
    let total=0;
    getters.addShopList.map(n=>{
      total += n.num*n.price
    })
    return total;
  },
}
const actions={
  //加入购物车
  addToCart({commit},product){
    commit('addCart',{
      id:product.id
    })
  },
  //清空购物车
  clearToCart({commit}){
    commit('clearCart')
  },
  //删除单个物品
  deletToShop({commit},product){
    commit('deletShop',product)
  }
}
const mutations ={
  //加入购物车
  addCart(state,{id}){
    let record = state.add.find(n => n.id == id);
    if(!record){
      state.add.push({
        id,
        num:1
      })
    }else{
      record.num++;
    }
  },
  //删除单个物品
  deletShop(state,product){
    state.add.forEach((item,i)=>{
      if(item.id == product.id){
        state.add.splice(i,1)
      }
    })
  },
  //清空购物车
  clearCart(state){
    state.add=[];
  }
}
 export default new Vuex.Store({
  state,
  getters,
  actions,
  mutations
})

3.商品列表:list.vue

<template>
  <div class="shop-list">
    <table>
      <tr class="shop-listtitle">
        <td>id</td>
        <td>名称</td>
        <td>价格</td>
        <td>操作</td>
      </tr>
      <tr v-for="item in shopList" class="shop-listinfo">
        <td>{{item.id}}</td>
        <td>{{item.name}}</td>
        <td>{{item.price}}</td>
        <td><button @click="addToCart(item)">加入购物车</button></td>
      </tr>
    </table>
		<button @click="toCart()">进入购物车</button>

  </div>
</template>
<script>
  import{mapActions} from "vuex";
  export default{
    name:'shopList',
    data(){
      return{
      }
    },
    computed:{
      shopList(){
        return this.$store.getters.getShopList
      }
    },
		created(){
			 this.$store.dispatch('getFood'); 
		},
    methods:{
      ...mapActions(['addToCart']),
			toCart(){
				this.$router.push("/cart")
			}
    }
  }
</script>


4.cart.vue

<template>
  <div class="shop-list">
    <table>
      <tr class="shop-listtitle">
        <td>id</td>
        <td>名称</td>
        <td>价格</td>
        <td>数量</td>
        <td>操作</td>
      </tr>
      <tr v-for="item in cartData" class="shop-listinfo">
        <td>{{item.id}}</td>
        <td>{{item.name}}</td>
        <td>{{item.price}}</td>
        <td>{{item.num}}</td>
        <td><button class="shop-dele dele-btn" @click="deletShop(item)">删除</button></td>
      </tr>
      <tr v-if="cartData.length<=0">
        <td colspan="5">暂无数据</td>
      </tr>
      <tr>
        <td colspan="2">总数:{{totalNum}}</td>
        <td colspan="2">总价格:{{totalPrice}}</td>
        <td><button class="dele-cart dele-btn" @click="clearCart">清空购物车</button></td>
      </tr>
    </table>
  </div>
</template>
<script>
  import {mapGetters,mapActions} from "vuex";
	
  export default{
    name:'shopCart',
    data(){
      return{
      }
    },
    computed:{
      ...mapGetters({
        cartData:'addShopList',
        totalNum:'totalNum',
        totalPrice:'totalPrice'
      })
    },
    methods:{
      ...mapActions({
        clearCart:'clearToCart',
        deletShop:'deletToShop'
      })
    }
  }
</script>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值