1. 程式人生 > 程式設計 >vuex實現購物車的增加減少移除

vuex實現購物車的增加減少移除

本文例項為大家分享了vuex實現購物車增加減少移除的具體程式碼,供大家參考,具體內容如下

1.store.js(公共的倉庫)

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
 
export default new Vuex.Store({
 state: {
  carList: [] //購物車的商品
 },mutations: {
  // 加
  addCar(state,params) {
   let CarCon = state.carList;
   // 判斷如果購物車是否有這個商品,有就只增加數量,否則就新增一個
   // some 只要有一個isHas為true,就為true
   let isHas = CarCon.some((item) => {
    if (params.id == item.id) {
     item.num++;
     return true;
    } else {
     return false;
    }
   })
 
   if (!isHas) {
    let obj = {
     "id": params.id,"title": params.title,"price": params.price,"num": 1,}
    this.state.carList.push(obj)
   }
  },// 減
  reducedCar(state,params){
   let len=state.carList.length;
   for(var i=0;i<len;i++){
    if(state.carList[i].id==params.id){
     state.carList[i].num--
     if(state.carList[i].num==0){
      state.carList.splice(i,1);
      break;
     }
    }
   }
  },//移出
  deleteCar(state,params){
   let len=state.carList.length;
   for(var i=0;i<len;i++){
    if(state.carList[i].id==params.id){
     state.carList.splice(i,1);
     break;
    }
   }
  },// 初始化購物車,有可能使用者一登入直接進入購物車
  // initCar(state,car) {
  //  state.carList = car
  // },},actions: {
  // 加
  addCar({ commit },params) {
   // console.log(params) //點選新增傳過來的引數
   // 使用setTimeout模擬非同步獲取購物車的資料
   setTimeout(function () {
    let result = 'ok'
    if (result == 'ok') {
     // 提交給mutations
     commit("addCar",params)
    }
   },100)
  },// 減
  reducedCar({ commit },params) {
   // console.log(params) //點選新增傳過來的引數
   // 使用setTimeout模擬非同步獲取購物車的資料
   setTimeout(function () {
    let result = 'ok'
    if (result == 'ok') {
     // 提交給mutations
     commit("reducedCar",// 移出
  deleteCar({ commit },params) {
   // console.log(params) //點選新增傳過來的引數
   // 使用setTimeout模擬非同步獲取購物車的資料
   setTimeout(function () {
    let result = 'ok'
    if (result == 'ok') {
     // 提交給mutations
     commit("deleteCar",100)
  }
  // initCar({ commit }) {
  //  setTimeout(function () {
  //   let result = 'ok'
  //   if (result == 'ok') {
  //    // 提交給mutations
  //    commit("initCar",[{
  //     "id": 20193698,//     "title": '我是購物車原來的',//     "price": 30,//     "num": 100,//    }])
  //   }
  //  },100)
  // }
 },getters: {
  //返回購物車的總價
  totalPrice(state) {
   let Carlen = state.carList;
   let money = 0;
   if (Carlen.length != 0) {
    Carlen.forEach((item) => {
     money += item.price * item.num
    })
    return money;
   } else {
    return 0;
   }
  },//返回購物車的總數
  carCount(state) {
   return state.carList.length
  }
 },})

2. list.vue(商品列表)

 <template>
 <!-- 商品列表 -->
 <div id="listBox">
 <!-- -->
 <router-link :to="{path:'/car'}" style="line-height:50px">跳轉到購物車</router-link>
 <el-table :data="tableData" border style="width: 100%">
  <el-table-column fixed prop="id" align="center" label="商品id"></el-table-column>
  <el-table-column prop="title" align="center" label="商品標題"></el-table-column>
  <el-table-column prop="price" align="center" label="商品價格"></el-table-column>
  <el-table-column label="操作" align="center">
  <template slot-scope="scope">
   <el-button @click="addCar(scope.row)" type="text" size="small">加入購物車</el-button>
  </template>
  </el-table-column>
 </el-table>
 </div>
</template>
 
<script>
export default {
 name: "listBox",data() {
 return {
  tableData: [] //商品列表
 };
 },methods: {
 // 初始化商品列表
 initTable(){
  this.$gAjax(`../static/shopList.json`)
  .then(res => {
   console.log(res)
   this.tableData=res;
  })["catch"](() => {});
 },// 加入購物車
 addCar(row){
  // console.log(row)
  // 提交給store裡面actions 由於加入購物車的資料要同步到後臺
  this.$store.dispatch('addCar',row)
 }
 
 },mounted () {
 this.initTable()
 }
};
</script>
<style>
#listBox {
 width: 900px;
 margin: 0 auto;
}
</style>

3. car.vue(購物車)

<template>
 <!-- 購物車 -->
 <div id="carBox">
 <!-- 商品總數 -->
 <h2 style="line-height:50px;font-size:16px;font-weight:bold">合計:總共{{count}}個商品,總價{{totalPrice}}元</h2>
 <p v-if="count==0">空空如也!·······</p>
 <div v-else>
  <el-table :data="carData" border style="width: 100%">
  <el-table-column fixed prop="id" align="center" label="商品id"></el-table-column>
  <el-table-column prop="title" align="center" label="商品標題"></el-table-column>
  <el-table-column prop="price" align="center" label="商品價格"></el-table-column>
  <el-table-column label="操作" align="center">
   <template slot-scope="scope">
   <el-button @click="reduceFun(scope.row)" type="text" size="small">-</el-button>
   <span >{{scope.row.num}}</span>
   <el-button @click="addCar(scope.row)" type="text" size="small">+</el-button>
 
   <el-button @click="deleteFun(scope.row)" type="text" size="small">刪除</el-button>
   </template>
  </el-table-column>
  </el-table>
 </div>
 </div>
</template>
 
<script>
export default {
 name: "carBox",data() {
 return {};
 },computed: {
 //購物車列表
 carData() {
  return this.$store.state.carList;
 },//商品總數
 count() {
  return this.$store.getters.carCount;
 },//商品總價
 totalPrice() {
  return this.$store.getters.totalPrice;
 }
 },methods: {
 // 增加數量
 addCar(row){
  this.$store.dispatch('addCar',row)
 },// 減數量
 reduceFun(row){
  this.$store.dispatch('reducedCar',// 刪除
 deleteFun(row){
  this.$store.dispatch('deleteCar',row)
 }
 
 // 使用者首次登入請求購物車的資料
 // initCar(){
 // this.$store.dispatch('initCar')
 // }
 },created () {
 // this.initCar();
 },mounted() {}
};
</script>
 
<style>
#carBox {
 width: 900px;
 margin: 0 auto;
}
</style>

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。