Vuex implements simple shopping cart function

Vuex implements simple shopping cart function

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

The file directory is as follows:

Shopping cart component

 <template>
    <div>
        <h1>vuex-shopCart</h1>
        <div class="shop-listbox">
            <shop-list />
        </div>
        <h2>Selected Products</h2>
        <div class="shop-cartbox">
            <shop-cart />
        </div>
    </div>
</template>

<script>
import shoList from './shop-list'
import shopCart from './shop-cart'

export default {
  name: 'shop',
  components:
      'shop-list' : shoList,
      'shop-cart' : shopCart
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>

Product List

 <template>
    <div class="shop-list">
        <table>
            <tr class="shop-listtitle">
                <td>id</td>
                <td>Name</td>
                <td>Price</td>
                <td>Operation</td>
            </tr>
            <tr v-for = "item in shopList" class="shop-listinfo" :key="item.id">
                <td>{{item.id}}</td>
                <td>{{item.name}}</td>
                <td>{{item.price}}</td>
                <td>
                    <button @click="addToCart(item)">Add to cart</button>
                </td>
            </tr>
        </table>
    </div>
</template>

<script>
import {mapGetters,mapActions} from "vuex";
export default {
    name : 'shopList',
    computed: {
        ...mapGetters({
                shopList:'getShopList',
            })
    },
    methods: {
        ...mapActions(['addToCart'])
    },
}
</script>

Selected product list

 <template>
    <div class="shop-list">
        <table>
            <tr class="shop-listtitle">
                <td>id</td>
                <td>Name</td>
                <td>Price</td>
                <td>Quantity</td>
                <td>Operation</td>
            </tr>
            <tr v-for="item in cartData" class="shop-listinfo" :key="item.id">
                <td>{{item.id}}</td>
                <td>{{item.name}}</td>
                <td>{{item.price}}</td>
                <td>{{item.num}}</td>
                <td><button class="shop-dele dele-btn" @click="deleteShop(item)">Delete</button></td>
            </tr>
            <tr v-if="cartData.length <= 0">
                <td colspan="5">No data</td>
            </tr>
            <tr>
                <td colspan="2">Total:{{totalNum}}</td>
                <td colspan="2">Total Price:{{totalPrice}}</td>
                <td><button class="dele-cart dele-btn" @click="clearCart">Clear shopping cart</button></td>
            </tr>
        </table>
    </div>
</template>

<script>
import {mapGetters,mapActions} from 'vuex'
export default {
    name : 'shopCart',
    data(){
        return {
            
        }
    },
    computed: {
        ...mapGetters({
            cartData:'addShopList',
            totalNum : 'totalNum',
            totalPrice:'totalPrice'
        })
    },
    methods: {
        ...mapActions({
            clearCart:'clearToCart',
            deleteShop:"deletToShop"
        })
    }
}
</script>

vuex creation

npm install vuex --save, create a vuex folder, create store.js in the folder, and introduce vuex;

store.js

 import Vue from "vue"
import Vuex from 'vuex'
import cart from './modules/cart'

Vue.use(Vuex)

export default new Vuex.Store({
    modules:
        cart
    }
})

Create a module folder modules, create a store module in it, output it by default, and introduce it in store.js;

cart.js

 const state = {
    shop_list: [{
        id: 11,
        name: 'Fish-flavored Shredded Pork',
        price : 12
    }, {
            id: 22,
            name: 'Kung Pao Chicken',
            price: 14
        }, {
            id: 34,
            name: 'Shredded Potatoes',
            price: 10
        }, {
            id: 47,
            name: 'rice',
            price : 2
        }, {
            id: 49,
            name: 'Ant Counting',
            price: 13
        }, {
            id: 50,
            name: 'Stir-fried bacon with garlic sprouts',
            price: 15
        }],
        add : []
}

const getters = {
    // Get the product list getShopList: state => state.shop_list,
    // Get the shopping cart list addShopList: state => {
        // The map() method returns a new array whose elements are the values ​​of the original array elements after calling the function return state.add.map(({ id, num }) => {
            let product = state.shop_list.find(n => n.id == id) // The find() method returns the value of the first element of the array that passes the test (judgment within the function). If no element meets the conditions, it returns undefined
            if (product) {// If the product exists return {// Return object...product,
                    num
                }
            }
        })
    },
     // Get the total number totalNum: (state, getters) => {
         let total = 0
         getters.addShopList.map(n => { 
             total += n.num
         })
         return total
    },
    // Calculate the total price totalPrice: (state, getters) => { 
        let total = 0
        getters.addShopList.map(n => { 
            total += n.num * n.price
        })
        return total
    }
},

const actions = {
    // Add to cart addToCart({ commit},product) { 
        commit('addCart', {
            id : product.id
        })
    },
    // Clear the shopping cart clearToCart({ commit}) { 
        commit('clearCart')
    },
    // Delete a single item deleteToShop({ commit},product) { 
        commit('deletShop',product)
    }
}

const mutations = {
    // Add to cart addCart(state, { id}){ 
        let record = state.add.find(n => n.id == id)
        if (!record) {// If the product does not exist in the shopping cart state.add.push({// Add product id,
                num : 1
            })
        } else { // If the product has been added to the shopping cart, change the quantity record.num++
        }
    },
    // Delete a single item deleteShop(state, product) { 
        state.add.forEach((item,i) => { 
            if (item.id == product.id) { // If the product is found state.add.splice(i,1)
            }
        })
    },
    // Clear the shopping cart clearCart(state) { 
        state.add = []
    }
}

export default {
    state,
    getters,
    actions,
    mutations
} 

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:
  • Vuex implements a simple shopping cart
  • 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

<<:  Detailed graphic tutorial on installation, startup and basic configuration of MySQL under Windows version

>>:  Docker's flexible implementation of building a PHP environment

Recommend

webpack -v error solution

background I want to check the webpack version, b...

Build Tomcat9 cluster through Nginx and realize session sharing

Use Nginx to build Tomcat9 cluster and Redis to r...

MySQL database basic syntax and operation

MySQL database basic syntax DDL Operations Create...

Detailed explanation of how to copy and backup docker container data

Here we take the Jenkins container as an example ...

WeChat applet realizes multi-line text scrolling effect

This article example shares the specific code for...

Examples of importing and exporting MySQL table data

This article describes the import and export oper...

Sample code for configuring nginx to support https

1. Introduction Are you still leaving your websit...

Detailed explanation of encoding issues during MySQL command line operations

1. Check the MySQL database encoding mysql -u use...

In-depth understanding of Vue transition and animation

1. When inserting, updating, or removing DOM elem...

Summary of MySQL time statistics methods

When doing database statistics, you often need to...

Basic application methods of javascript embedded and external links

Table of contents Basic application of javascript...

JavaScript implements simple calculator function

This article example shares the specific code of ...

Summary of common Mysql DDL operations

Library Management Create a library create databa...

Analysis of JavaScript's event loop mechanism

Table of contents Preface: 1. Reasons for the eve...