美文网首页
关于vuex购物车实现的原理

关于vuex购物车实现的原理

作者: 千锋H5 | 来源:发表于2018-08-29 14:09 被阅读243次

1、模拟购物车功能

   创建store/cart.js

export default {

  state:{

    cartlist: []

  },

  getters: {

  },

  actions: {

  },

  mutations: {

  }

}

2、添加该模块到状态管理器

import Vue from 'vue'

import Vuex from 'vuex'

import cart from './cart.js'

Vue.use(Vuex)

const store = new Vuex.Store({

  modules: {

    cart

  }

})

export default store

3、cart组件中script.js

import {mapState} from 'vuex'

export default {

  computed: {

    ...mapState({

      'cartlist': ({cart}) => cart.cartlist

    })

  }

}

4、在store/cart.js中请求购物车数据

export default {

  state:{

    cartlist: []

  },

  getters: {

  },

  actions: {

        getCartlist ({commit}) {

              cartapi.getCartlist((data) => {commit('changeCartlist', data)})

        }

  },

  mutations: {

  }

}

5、实现请求数据的方法api/cart.js

import axios from 'axios'

export default {

  getCartlist (cb) {

    // axios请求数据,请求成功调用回调函数cb  ----   模拟数据data

    var data = [

      {id:1,name:'pro1',num:1,price:10},

      {id:2,name:'pro2',num:2,price:20},

      {id:3,name:'pro3',num:3,price:30},

      {id:4,name:'pro4',num:4,price:40}

    ]

    cb(data)

  }

}

6、实现提交mutation改变cartlist----store/cart.js

export default {

  state:{

    cartlist: []

  },

  getters: {

  },

  actions: {

        getCartlist ({commit}) {

              cartapi.getCartlist((data) => {commit('changeCartlist', data)})

        }

  },

  mutations: {

        changeCartlist (state, data) {

          state.cartlist = data

        },

  }

}

7、触发请求数据----cart组件中分发action----script.js

import {mapState} from 'vuex'

export default {

  computed: {

    ...mapState({

      'cartlist': ({cart}) => cart.cartlist

    })

  },

  mounted () {

    this.$store.dispatch('getCartlist')

  }

}

8、计算商品的总数量和总价

    8.1 store/cart.js中添加选项getters

export default {

  state:{

    cartlist: []

  },

  getters: {

    totalCount(state){

      let totalNum = 0

      let totalPrice = 0

      state.cartlist.filter((item) => {

          totalNum += item.num * 1

          totalPrice += item.num * item.price

      })

      return {

        totalNum,

        totalPrice

      }

    }

  },

  actions: {

        getCartlist ({commit}) {

              cartapi.getCartlist((data) => {commit('changeCartlist', data)})

        }

  },

  mutations: {

        changeCartlist (state, data) {

          state.cartlist = data

        },

  }

}

    8.2 cart组件中index.vue使用即可

        8.2.1    直接获取store中的getters

总量:{{this.$store.getters.totalCount.totalNum}}

 

总价:{{this.$store.getters.totalCount.totalPrice}}

        8.2.2   使用mapGetters辅助函数减少代码量

    script.js

import {mapState,mapGetters} from 'vuex'

export default {

  computed: {

    ...mapState({

      'cartlist': ({cart}) => cart.cartlist

    }),

    mapGetters(['totalCount'])

  },

  mounted () {

    this.$store.dispatch('getCartlist')

  }

}

    index.vue

总量:{{totalCount.totalNum}}

 

总价:{{totalCount.totalPrice}}

9、选择商品计算价格和数量

    9.1 index.vue布局

  

    

            

  •         

            {{ item.name}} ---- {{item.num}} ---- {{item.price}} -

        

    总量:{{totalCount.totalNum}}

        

    总价:{{totalCount.totalPrice}}

        9.2 改造源数据 api/cart.js

    import axios from 'axios'

    export default {

      getCartlist (cb) {

        // axios请求数据,请求成功调用回调函数cb  ----   模拟数据data

        var data = [

          {id:1,name:'pro1',num:1,price:10},

          {id:2,name:'pro2',num:2,price:20},

          {id:3,name:'pro3',num:3,price:30},

          {id:4,name:'pro4',num:4,price:40}

        ]

        data.map((item) => {

          item.flag = false

        })

        cb(data)

      }

    }

    10、 实现全选和反选功能

        10.1 index.vue布局

      

    全选

        

              

    •         

              {{ item.name}} ---- {{item.num}} ---- {{item.price}} -

          

      总量:{{totalCount.totalNum}}

          

      总价:{{totalCount.totalPrice}}

          10.2 store/cart.js添加新的初始值 allSelected

      export default {

        state:{

          cartlist: [],

          allSelected: false

        },

        getters: {

          totalCount(state){

            let totalNum = 0

            let totalPrice = 0

            state.cartlist.filter((item) => {

                totalNum += item.num * 1

                totalPrice += item.num * item.price

            })

            return {

              totalNum,

              totalPrice

            }

          }

        },

        actions: {

              getCartlist ({commit}) {

                    cartapi.getCartlist((data) => {commit('changeCartlist', data)})

              }

        },

        mutations: {

              changeCartlist (state, data) {

                state.cartlist = data

              },

        }

      }

          10.3 cart组件中添加全选事件

      //index.vue

      全选

      // script.js 中的methods

      selectFn (cartlist) {

             this.$store.commit('changeAllSelect')  // 切换真假

              //改变store中数据后立马请求其值

             if(this.$store.state.cart.allSelected){ //  如果为真,表示全部要被选中

               const flag = true  // 标志为真

               this.$store.dispatch('getAllSelectCartlist', {cartlist, flag} ) // action中设置所有元素为真

             }else{

               const flag = false

               this.$store.dispatch('getAllSelectCartlist', {cartlist, flag} )

             }

           },

          10.4 实现changeAllSelect mutation 和 getAllSelectCartlist action

              store/cart.js

      export default {

        state:{

          cartlist: [],

          allSelected: false

        },

        getters: {

          totalCount(state){

            let totalNum = 0

            let totalPrice = 0

            state.cartlist.filter((item) => {

                totalNum += item.num * 1

                totalPrice += item.num * item.price

            })

            return {

              totalNum,

              totalPrice

            }

          }

        },

        actions: {

              getCartlist ({commit}) {

                    cartapi.getCartlist((data) => {commit('changeCartlist', data)})

              },

               getAllSelectCartlist ({commit}, {cartlist, flag}) {

            cartlist.map((item) => {

              item.flag = flag

            })

            commit('changeCartlist', cartlist)

      },

        },

        mutations: {

              changeCartlist (state, data) {

                state.cartlist = data

              },

               changeAllSelect (state) {

            state.allSelected = !state.allSelected

      },

        }

      }

      11、点击列表选择实现全选和反选

                

      •         

                {{

        item.name}} ---- {{item.num}} ---- {{item.price}} --

        @click="deleteItem(cartlist, index)">删除

        script.js

        selectItem (cartlist, item, index) {

               if(item.flag){

                 const flag = true

                 this.$store.dispatch('selectItem', {cartlist, index, flag}) // cartlist[index].flag = flag

               }else {

                 const flag = false

                 this.$store.dispatch('selectItem', {cartlist, index, flag})

               }

               // console.log("cartlist",this.$store.state.cart.cartlist)

               var cartlist = this.$store.state.cart.cartlist

               this.$store.dispatch('checkItem',cartlist) // 每做出一次选择就去检测要不要全选

             }

        实现action selectItem 和checkItem   store/cart.js

        export default {

          state:{

            cartlist: [],

            allSelected: false

          },

          getters: {

            totalCount(state){

              let totalNum = 0

              let totalPrice = 0

              state.cartlist.filter((item) => {

                  totalNum += item.num * 1

                  totalPrice += item.num * item.price

              })

              return {

                totalNum,

                totalPrice

              }

            }

          },

          actions: {

                getCartlist ({commit}) {

                      cartapi.getCartlist((data) => {commit('changeCartlist', data)})

                },

                 getAllSelectCartlist ({commit}, {cartlist, flag}) {

              cartlist.map((item) => {

                item.flag = flag

              })

              commit('changeCartlist', cartlist)

            },

        selectItem ({commit}, {cartlist, index, flag}) {

              cartlist[index].flag = flag

              commit('changeCartlist', cartlist)

            },

            checkItem ({commit}, cartlist){

              let all = true

              cartlist.map((item) => {

                if(!item.flag) {

                  all = false

                }

              })

              commit('checkCartlist', all)

            }

          },

          mutations: {

                changeCartlist (state, data) {

                  state.cartlist = data

                },

                 changeAllSelect (state) {

              state.allSelected = !state.allSelected

            },

          }

        }

        实现mutation checkCartlist

        export default {

          state:{

            cartlist: [],

            allSelected: false

          },

          getters: {

            totalCount(state){

              let totalNum = 0

              let totalPrice = 0

              state.cartlist.filter((item) => {

                  totalNum += item.num * 1

                  totalPrice += item.num * item.price

              })

              return {

                totalNum,

                totalPrice

              }

            }

          },

          actions: {

                getCartlist ({commit}) {

                      cartapi.getCartlist((data) => {commit('changeCartlist', data)})

                },

                 getAllSelectCartlist ({commit}, {cartlist, flag}) {

              cartlist.map((item) => {

                item.flag = flag

              })

              commit('changeCartlist', cartlist)

            },

        selectItem ({commit}, {cartlist, index, flag}) {

              cartlist[index].flag = flag

              commit('changeCartlist', cartlist)

            },

            checkItem ({commit}, cartlist){

              let all = true

              cartlist.map((item) => {

                if(!item.flag) {

                  all = false

                }

              })

              commit('checkCartlist', all)

            }

          },

          mutations: {

                changeCartlist (state, data) {

                  state.cartlist = data

                },

                 changeAllSelect (state) {

              state.allSelected = !state.allSelected

            },

        checkCartlist (state, data) {

              state.allSelected = data

            }

          }

        }

        12、删除操作

                  

        •         

                  {{

          item.name}} ---- {{item.num}} ---- {{item.price}} --

          @click="deleteItem(cartlist, index)">删除

          deleteItem (cartlist, index) {

                 this.$store.dispatch('deleteItem', {cartlist, index})

               },

          store/cart.js

          export default {

            state:{

              cartlist: [],

              allSelected: false

            },

            getters: {

              totalCount(state){

                let totalNum = 0

                let totalPrice = 0

                state.cartlist.filter((item) => {

                    totalNum += item.num * 1

                    totalPrice += item.num * item.price

                })

                return {

                  totalNum,

                  totalPrice

                }

              }

            },

            actions: {

                  getCartlist ({commit}) {

                        cartapi.getCartlist((data) => {commit('changeCartlist', data)})

                  },

                   getAllSelectCartlist ({commit}, {cartlist, flag}) {

                cartlist.map((item) => {

                  item.flag = flag

                })

                commit('changeCartlist', cartlist)

              },

          selectItem ({commit}, {cartlist, index, flag}) {

                cartlist[index].flag = flag

                commit('changeCartlist', cartlist)

              },

              checkItem ({commit}, cartlist){

                let all = true

                cartlist.map((item) => {

                  if(!item.flag) {

                    all = false

                  }

                })

                commit('checkCartlist', all)

              },

          deleteItem ({commit}, {cartlist, index}) {

                cartapi.deleteItem({cartlist, index}, (data) => {commit('changeCartlist', data)})

              },

            },

            mutations: {

                  changeCartlist (state, data) {

                    state.cartlist = data

                  },

                   changeAllSelect (state) {

                state.allSelected = !state.allSelected

              },

          checkCartlist (state, data) {

                state.allSelected = data

              }

            }

          }

          api/cart.js

          import axios from 'axios'

          export default {

            getCartlist (cb) {

              // axios请求数据,请求成功调用回调函数cb  ----   模拟数据data

              var data = [

                {id:1,name:'pro1',num:1,price:10},

                {id:2,name:'pro2',num:2,price:20},

                {id:3,name:'pro3',num:3,price:30},

                {id:4,name:'pro4',num:4,price:40}

              ]

              data.map((item) => {

                item.flag = false

              })

              cb(data)

            },

            deleteItem ({cartlist, index}, cb) {

              cartlist.splice(index, 1)

              cb(cartlist)

            }

          }

          编辑:千锋HTML5​

        • 相关文章

          • 关于vuex购物车实现的原理

            1、模拟购物车功能 创建store/cart.js export default { state:{ cartl...

          • Vuex 状态管理

            Vue组件间通信方式 Vuex核心概念和基本使用 购物车案例 模拟实现vuex 一、组件内的状态管理流程 状态管理...

          • vuex源码分析(三)——Module和ModuleCollec

            本文参考珠峰架构公开课之vuex实现原理 在使用vuex过程中,如果数据量很大可以用vuex的modules实现模...

          • Vue实战(四) - 实战项目(下) - 路由初步/复杂状态管理

            0. 实战场景介绍 通过Vuex构建全局状态管理的购物车。通过路由功能实现购物车的跳转。 1. 创建空白购物车 s...

          • vuex实现原理

            vuex是vue的一个数据状态管理工具,简单的来说他就是一个vue的仓库用来存储vue的数据方便组件之间的调用。 ...

          • vuex实现原理

            以下内容是引用或者借鉴别人的,自己只是做个笔记,方便学习。理解错误的地方,欢迎评论。如有侵权,私聊我删除,未经允许...

          • vuex实现原理

            思路及流程 vuex是在每个组件上注入this.store获取共享的状态,定义操作state的方法。首先使用vue...

          • vuex源码分析(一)——初始化vuex

            本文参考珠峰架构公开课之vuex实现原理 vuex是基于vue框架的状态管理。 如何在vue项目中初始化vuex?...

          • 2019-10-09 面试

            1,css3新特性2,vue路由和实现原理3,vuex的实现原理4,webpack打包的过程,loading和pl...

          • Vuex 的学习过程记录

            Vuex 的学习记录 资料参考网址Vuex中文官网Vuex项目结构示例 -- 购物车Vuex 通俗版教程Nuxt....

          网友评论

              本文标题:关于vuex购物车实现的原理

              本文链接:https://www.haomeiwen.com/subject/bmohwftx.html