Vuex implements a simple shopping cart

Vuex implements a simple shopping cart

This article example shares the specific code of Vuex to implement a simple shopping cart for your reference. The specific content is as follows

File Structure

App.vue

<template>
 <div id="app">
 <h3>Shopping Cart Demo</h3>
 <hr>
 <h4>Products:</h4>
 <ProductList />
 <hr>
 <h4>My Cart</h4>
 <ShoppingCart />
 </div>
</template>
<script>
import ProductList from '@/components/ProductList';
import ShoppingCart from '@/components/ShoppingCart';
 
export default {
 components:
 ProductList,
 ShoppingCart
 }
}
</script>

Products.vue

<template>
 <div>
  <ul v-for="item in products" :key="item.id">
  <li>
   {{ item.title }} - {{ item.price }} &nbsp;&nbsp; Inventory: {{ item.inventory }}<br>
   <button :disabled="!item.inventory" @click="addToCart(item)">add to cart</button> 
  </li>
  </ul>
 </div>
 
</template>
 
<script>
import { mapGetters, mapActions } from 'vuex';
export default {
 computed: {
 // ...mapGetters('products',{
 // products: 'allProducts'
 // })
 ...mapGetters({
  products: 'products/allProducts'
 })
 },
 methods: {
 ...mapActions('cart',['addToCart'])
 },
 created() {
 this.$store.dispatch('products/getAllProducts');
 }
 
}
</script>

ShoppingCart.vue

<template>
 <div>
 <ul v-for="item in products" :key="item.id">
  <li>{{ item.title }} *{{ item.quantity }}</li>
 </ul>
 <div>total: {{ total }}</div>
 </div>
</template>
<script>
import { mapGetters } from 'vuex';
export default {
 computed: {
 ...mapGetters('cart', {
  products: 'cartProducts',
  total: 'cartTotalPrice'
 })
 }
}
</script>

modules/products.js

import api from '../../api';
 
const state = {
 all: []
}
 
const getters = {
 allProducts: state => state.all
}
 
const actions = {
 // Get initial product data getAllProducts({ commit }) {
 api.getProducts(products => commit('setProducts', products));
 }
}
 
const mutations = {
 setProducts(state, products) {
 state.all = products;
 },
 // Reduce the inventory of this product decreamentInventory(state, { id }) {
 let productItem = state.all.find(item => item.id === id);
 productItem.inventory --;
 }
}
 
export default {
 namespaced: true,
 state,
 getters,
 actions,
 mutations
}

modules/cart.js

const state = {
 addedList: []
}
 
const getters = {
 cartProducts(state, getters, rootState) {
 return state.addedList.map((item, index) => {
  let productItem = rootState.products.all.find(product => product.id === item.id);
  return {
  title: productItem.title,
  price: productItem.price,
  quantity: item.quantity
  }
 })
 },
 cartTotalPrice(state, getters) {
 return getters.cartProducts.reduce((total, product) => {
  return total + (product.price * product.quantity);
 }, 0);
 }
}
 
const actions = {
 addToCart({ state, commit }, product) {
 if (product.inventory > 0) {
  let productItem = state.addedList.find(item => item.id === product.id);
  if (productItem) {
  commit('increamentItemQuantity', productItem);
  } else {
  commit('pushItemToCart', product);
  }
  commit('products/decreamentInventory', product, { root: true });
 }
 }
}
 
const mutations = {
 // Increase the number of identical items in the shopping cart increaseItemQuantity(state, { id }) {
 let productItem = state.addedList.find(item => item.id === id);
 productItem.quantity++;
 },
 // Add the item to the shopping cart pushItemToCart(state, { id }) {
 state.addedList.push({
  id,
  quantity: 1
 })
 },
 
}
 
export default {
 namespaced: true,
 state,
 getters,
 actions,
 mutations
}

store/index.js

import Vue from 'vue';
import Vuex from 'vuex';
import cart from './modules/cart';
import products from './modules/products';
 
Vue.use(Vuex);
 
export default new Vuex.Store({
 modules:
 cart,
 products
 }
});

main.js

import Vue from "vue";
import App from "@/components/App.vue";
import store from "@/store";
 
Vue.config.productionTip = false;
 
new Vue({
 store,
 render: h => h(App)
}).$mount("#app");

The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM.

You may also be interested in:
  • Implementing shopping cart function based on vuex
  • Vuex implements small shopping cart function
  • Vuex implements adding, reducing and removing shopping carts
  • Vuex realizes shopping cart function
  • Example code for using vuex to elegantly implement a shopping cart function
  • Simple shopping cart function example implemented by vuex
  • I wrote a sample code for a shopping cart H5 page using vuex
  • Vuex implements simple shopping cart function

<<:  An example of implementing a simple infinite loop scrolling animation in Vue

>>:  JS realizes the scrolling effect of announcement online

Recommend

How to build a complete samba server in Linux (centos version)

Preface smb is the name of a protocol that can be...

Detailed explanation of the code for implementing linear gradients with CSS3

Preface The gradient of the old version of the br...

Summary of naming conventions for HTML and CSS

CSS naming rules header: header Content: content/c...

MySQL index pushdown details

Table of contents 1. Leftmost prefix principle 2....

Detailed explanation of the 4 codes that turn the website black, white and gray

The 2008.5.12 Wenchuan earthquake in Sichuan took...

Simple method to install mysql under linux

When searching online for methods to install MySQ...

Example of pre-rendering method for Vue single page application

Table of contents Preface vue-cli 2.0 version vue...

Google Translate Tool: Quickly implement multilingual websites

Google China has released a translation tool that ...

React method of displaying data in pages

Table of contents Parent component listBox List c...

Linux Disk Quota Management Graphical Example

Disk quota is the storage limit of a specified di...

Why node.js is not suitable for large projects

Table of contents Preface 1. Application componen...

Application example tutorial of key in Vue page rendering

introduction During the front-end project develop...

Does the % in the newly created MySQL user include localhost?

Normal explanation % means any client can connect...

Detailed example of using if statement in mysql stored procedure

This article uses an example to illustrate the us...