Source code learning in the Vuex project Example (3)

Shopping cart

Project Overview

insert image description here
From the running screenshot, it is not difficult to see that it is a simple product shopping page. products should get all product data from vuex. The product has a certain amount of inventory. Every time it is added to the shopping cart, it will be reduced by one. When it reaches 0, it cannot be purchased. Your cart is a shopping cart. Every time you click to buy, an item will be added to the shopping cart. At the same time, an item will be added to the shopping cart, and the shopping cart has a summary of the amount. Then click checkout, which will occasionally succeed and occasionally fail.

Speculate on the realization of the program

I personally think that writing code itself is solving problems. Reading code is to understand the thinking of others to solve problems. So before reading, it is best to think about yourself, if you write this code yourself, how will you write it. Then compare other people's code so that you can learn in depth.

personal thoughts

Two Modules can be created, one for products and one for shopping carts.

The Module that stores products needs to save all product data in state, and then there needs to be an addToCart method in mutations. There is also a getters, need to get all the products. addTOCart is responsible for reducing the number of items in the warehouse. And getters for all items need to get information about items in all warehouses.

To store your cart, you need to store all the shopping cart data and the summed amount in the state, and you need the addToCart method in Mutations to add items. Checkout is responsible for emptying all shopping carts. Preferably also have a getters to calculate the price of all items.

Then two components can be created on the page, a product list and a shopping cart.

Project directory structure

insert image description here

project realization

API section

const _products = [
  {
    
     'id': 1, 'title': 'iPad 4 Mini', 'price': 500.01, 'inventory': 2 },
  {
    
     'id': 2, 'title': 'H&M T-Shirt White', 'price': 10.99, 'inventory': 10 },
  {
    
     'id': 3, 'title': 'Charli XCX - Sucker CD', 'price': 19.99, 'inventory': 5 }
]

export default {
    
    
  getProducts (cb) {
    
    
    setTimeout(() => cb(_products), 100)
  },

  buyProducts (products, cb, errorCb) {
    
    
    setTimeout(() => {
    
    
      // simulate random checkout failure.
      (Math.random() > 0.5 || navigator.webdriver)
        ? cb()
        : errorCb()
    }, 100)
  }
}

This part is not in our thinking, and the thinking in the project is more comprehensive and perfect mocking the server side. Made two functions, one to obtain product information, and the other to submit shopping cart information. Then use the callback function to send the information obtained from the server back to the state.

products.js

import shop from '../../api/shop'

// initial state
const state = () => ({
    
    
  all: []
})

// getters
const getters = {
    
    }

// actions
const actions = {
    
    
  getAllProducts ({
    
     commit }) {
    
    
    shop.getProducts(products => {
    
    
      commit('setProducts', products)
    })
  }
}

// mutations
const mutations = {
    
    
  setProducts (state, products) {
    
    
    state.all = products
  },

  decrementProductInventory (state, {
    
     id }) {
    
    
    const product = state.all.find(product => product.id === id)
    product.inventory--
  }
}

export default {
    
    
  namespaced: true,
  state,
  getters,
  actions,
  mutations
}

Compared with our idea, add an action to call to get all the products, and commit to setting the products. Of course, there is also a method to initialize the product data. In addition, there is no way to get all the products.

cart.js

import shop from '../../api/shop'

// initial state
// shape: [{ id, quantity }]
const state = () => ({
    
    
  items: [],
  checkoutStatus: null
})

// getters
const getters = {
    
    
  cartProducts: (state, getters, rootState) => {
    
    
    return state.items.map(({
    
     id, quantity }) => {
    
    
      const product = rootState.products.all.find(product => product.id === id)
      return {
    
    
        title: product.title,
        price: product.price,
        quantity
      }
    })
  },

  cartTotalPrice: (state, getters) => {
    
    
    return getters.cartProducts.reduce((total, product) => {
    
    
      return total + product.price * product.quantity
    }, 0)
  }
}

// actions
const actions = {
    
    
  checkout ({
    
     commit, state }, products) {
    
    
    const savedCartItems = [...state.items]
    commit('setCheckoutStatus', null)
    // empty cart
    commit('setCartItems', {
    
     items: [] })
    shop.buyProducts(
      products,
      () => commit('setCheckoutStatus', 'successful'),
      () => {
    
    
        commit('setCheckoutStatus', 'failed')
        // rollback to the cart saved before sending the request
        commit('setCartItems', {
    
     items: savedCartItems })
      }
    )
  },

  addProductToCart ({
    
     state, commit }, product) {
    
    
    commit('setCheckoutStatus', null)
    if (product.inventory > 0) {
    
    
      const cartItem = state.items.find(item => item.id === product.id)
      if (!cartItem) {
    
    
        commit('pushProductToCart', {
    
     id: product.id })
      } else {
    
    
        commit('incrementItemQuantity', cartItem)
      }
      // remove 1 item from stock
      commit('products/decrementProductInventory', {
    
     id: product.id }, {
    
     root: true })
    }
  }
}

// mutations
const mutations = {
    
    
  pushProductToCart (state, {
    
     id }) {
    
    
    state.items.push({
    
    
      id,
      quantity: 1
    })
  },

  incrementItemQuantity (state, {
    
     id }) {
    
    
    const cartItem = state.items.find(item => item.id === id)
    cartItem.quantity++
  },

  setCartItems (state, {
    
     items }) {
    
    
    state.items = items
  },

  setCheckoutStatus (state, status) {
    
    
    state.checkoutStatus = status
  }
}

export default {
    
    
  namespaced: true,
  state,
  getters,
  actions,
  mutations
}


Guess you like

Origin blog.csdn.net/aofengdaxia/article/details/114583086