Create modules and components

The module

Create modules modules in the Store folder, create cart.js and products.js modules in the store folder, associate the two modules with store index.js and import the two modules in index.js. And mount both modules in the Modules property.


index.js

/ / import
import cart from './modules/cart';
import products from './modules/products';


/ / a mount
  modules: {
    cart,
    products
  }
Copy the code

component

Because the example does not involve route jumps, create the product component ProductList and the ShoppingCart component ShoppingCart directly in components.

The background data

Create the vue. Config. js file in the project directory, configure devServer, restart the project, obtain the background data at the same time to initiate a request, need to install AXIos, terminal input NPM I axios -s to install.

Note: Every time this file is modified, you need to restart the project to take effect.


vue.config.js

const products = [{
    id: 1.title: 'Redmi 10'.price: 2200.inventory: 12
}, {
    id: 2.title: 'Redmi 10 pro'.price: 2800.inventory: 18
}, {
    id: 3.title: 'Redmi 10 max'.price: 3200.inventory: 8
}]

module.exports = {
    devServer: {
        before(app, serve) {
            app.get('/api/products'.(req, res) = > {
                res.json({
                    results: products
                })
            })
        }
    }
}
Copy the code

Module and component development

Products. Js module

/ / import axios
import axios from "axios"

export default {
    namespaced: true.state: {
        products: []},getters: {},
    mutations: {
        // Fetch data from the background
        getProductsFromServe(state, products) {
            state.products = products;
        },
        // Add to shopping cart, inventory minus 1
        decreaseProductsInventory(state, { id }) {
            // Find if the id of the item added to the cart is the same as the id of the item in the shop, and subtract one from the inventory
            const product = state.products.find(item= >item.id === id); product.inventory--; }},actions: {
        // Get data from the background
        async getProductsFromServe({ commit }) {
            // Send a request for data submit mutations
            try {
                const res = await axios.get('/api/products');
                //console.log(res.data.results);
                const results = res.data.results;
                / / submit
                commit('getProductsFromServe', results);
            } catch (error) {
                console.log(error); }}}}Copy the code

Cart. Js module

The rootState parameter is required to obtain the status of other modules in the current module, and the {root:true} parameter is required when the current module is submitted to another module

export default {
    namespaced: true.state: {
        cartList: [].count: 0
    },
    getters: {
        // Get the shopping cart data
        //rootState gets the root object index.js to get the product information in the Cart module
        RootState is required when one module fetches data from another module
        getCartList(state, getters, rootState) {
            //console.log(rootState);
            //{id,quantity} deconstructs each item in the cartList
            return state.cartList.map(({ id, quantity }) = > {
                // Whether the id of the item in the cart is the same as that of the current item
                const product = rootState.products.products.find(item= > item.id === id);
                return {
                    title: product.title,
                    price: product.price,
                    quantity: quantity
                }
            })
        },
        // The method in getters can be obtained via getters
        // Calculate the total price
        getTotalPrice(state, getters) {
            return getters.getCartList.reduce((total, product) = > {
                return total += product.price * product.quantity
            }, 0)}},mutations: {
        // Add an item to the cart for the first time
        pushProductToCart(state, { id, quantity }) {
            state.cartList.push({
                id,
                quantity
            })
        },
        // Only change the current amount of data in the shopping cart
        addCartItemQuantity(state, { id }) {
            // Find the currently added item in the shopping cart and add quantity +1
            const product = state.cartList.find(item= >item.id === id); product.quantity++; }},actions: {
    	// Add items to cart
        addProductToCart({ commit, state }, product) {
            //console.log(product);
            // Check whether there is inventory
            if (product.inventory > 0) {
                // Check if it is the first time
                const cartItem = state.cartList.find(item= > item.id === product.id);
                //console.log(cartItem);
                // If not found, it is the first time to add
                if(! cartItem) { commit('pushProductToCart', {
                        id: product.id,
                        quantity: 1})}else {
                    // The item has been added to the cart, proceed to quantity +1
                    commit('addCartItemQuantity', {
                        id: product.id
                    })
                }
                // Inventory is reduced by 1 and submitted to the decreaseInventory method in the Products module
                // When submitting from one module to another, be sure to add a third argument {root:true}
                commit('products/decreaseProductsInventory', {
                    id: product.id
                }, {
                    root: true}); }}}}Copy the code

ProductList components

<template>
  <div>
    <h2>shops</h2>
    <ul>
      <li>{{product}} - {{price}} - {{inventory}}</li>
      <li v-for="product in products" :key="product.id">
        {{product.title}} - {{product.price | currency}} - {{product.inventory}}
        <! -- When inventory is 0, disable button -->
        <button :disabled=! "" product.inventory" @click="addProductToCart(product)">Add to shopping cart</button>
      </li>
    </ul>
  </div>
</template>

<script>
// Import the helper function
import { mapState, mapActions } from "vuex";
  
export default {
  name: "ProductList".data() {
    return {
      product: "Products".price: "Price".inventory: "Inventory"}; },computed: {
  // Get the products status in the products module. mapState("products"["products"]),},created() {
    // Trigger the methods in the Products module to get background data and render the list
    this.$store.dispatch("products/getProductsFromServe");
  },
  methods: {
    // Get the addProductToCart method of the cart module. mapActions("cart"["addProductToCart"]),}};</script>

<style scoped>
</style>
Copy the code

ShoppingCart component

<template>
  <div>
    <h2>My shopping cart</h2>
    <ul>
      <li
        v-for="(item,index) in getCartList"
        :key="index"
      >{{item.title}} - {{item.price | currency}} x {{item.quantity}}</li>
    </ul>
    <! Select * from currency where name = 'currency';
    <h2>Total price: {{getTotalPrice | currency}}</h2>
  </div>
</template>

<script>
  // Import the helper function
import { mapGetters } from "vuex";
export default {
  name: "ShoppingCart".// Component name, used when registering global components
  computed: {
    ...mapGetters("cart"["getCartList"."getTotalPrice"]),}};</script>

<style scoped>
</style>
Copy the code

Register global components, filters

You need to register in main.js, which is the entry file for the entire project.

Registering global components

The component is first imported and then registered, either by name or by the name attribute thrown by the component.

// Import components
import ShoppingCart from '@/components/ShoppingCart'

// Globally register components
//Vue.component('ShoppingCart', ShoppingCart)
// Use the component name thrown by the component
Vue.component(ShoppingCart.name, ShoppingCart)
Copy the code

Register global filters

// Global register filter
Vue.filter('currency'.(value) = > A '$' + value)
Copy the code

Import a Vuex plug-in

Import in index.js in the store folder

// Import the log plug-in
import createLogger from 'vuex/dist/logger'
Copy the code

Then mount it using the plugins attribute

export default new Vuex.Store({
  // The logging plug-in is equivalent to integrating Vue Devtools
  plugins: [createLogger({
    // Automatically expand the mutation of the record
    collapsed: false})],})Copy the code