A simple way to implement all functions of shopping cart in Vue

A simple way to implement all functions of shopping cart in Vue

The main functions are as follows:

  1. Add product information
  2. Modify product information
  3. Deleting a single product
  4. Deleting multiple products
  5. Empty Cart
  6. Sort the product prices in descending order
  7. Search by product name
  8. Add or subtract the quantity of goods
  9. Select All Invert
  10. Calculate the total price of selected items

The effect diagram is as follows:

Since there are many functions, we will not talk about them one by one. Let's first talk about the logic of several main functions (add, delete, modify, and query), and finally put all the code.

First, let’s look at adding product features

//First, let's bind a button to display the event. After clicking Add, a pop-up window will appear <button type="button" @click="xian">Add</button>
//return defines a dis default value of false
 xian() {
                if (!this.dis == false) {
                    this.dis = false
                } else {
                    this.dis = true
                }
            },

Then click Confirm Change in the pop-up window and bind an event to add the product information.

           <button type="button" @click="tian">Confirm to add</button>
 //Push the product information to be added to a new array and close the pop-up window after adding tian() {
                if (this.name == "" || this.county == "" || this.price == "") {
                    alert("Product information cannot be empty!")
                    return false
                } else {

                    this.shopPings.push({
                        name: this.name,
                        counrty: this.counrty,
                        price: this.price,
                        count: this.count,
                    })
                }
                this.name = "",
                    this.counrty = "",
                    this.price = "",
                    this.count = ""
                this.dis = false
            },

After adding the product, I suddenly found that the product information was written incorrectly! ! ? ? Don't panic, let me show you how to modify the function

As usual, first define a button to bind the display event, and then bind the display event. Except for the event name, it is the same as adding it above. Let's look at the confirmation modification function directly.

//Define button binding event <button type="button" @click="xiugai">Confirm modification</button>
   //Modify the product information in the shopping cart and close the pop-up window after the modification. xiugai() {
                console.log(this.int)
                let index = this.int
                console.log(this.name, this.price, this.count, )
                this.shopPings[index].name = this.name
                this.shopPings[index].price = this.price
                this.shopPings[index].county = this.county
                this.shopPings[index].count = this.count

                this.dis1 = false
            },

After adding modifications, let's write a deletion

Define a button binding event, pass in an index value, and finally splice deletes an item based on the index.

Define a button binding event, pass in an index value, and finally splice deletes an item according to the subscript <button @click="del(index)">Delete</button>	
  del(index) {
                this.shopPings.splice(index, 1);
            },

Clearing the shopping cart is relatively simple. Just set the array to empty after clicking the button.

 alldel() {
                this.shopPings = []
            },

Finally, let’s take a look at the query function in the shopping cart

//Set the input value in return //Define an input box, bind the value, set the enter keyboard event and bind the search event <input type="text" placeholder="Please enter the name of the product to be queried" v-model="input_value" @keyup.13="search">

See the notes for details

//First, let's make a judgment. When the search box is empty, there will be a prompt message that it is not allowed to be empty. //Then get the name of each item in the array for search. If there is no such product name, it will prompt that there is no such product. //Finally, filter the array filter and find the corresponding product by comparing the product name entered in the search box with the product name in the shopping cart. search() {
                if (!this.input_value) {
                    return alert('Please enter content')
                }
                if (
                    this.shopPings.every((v) => {
                        v.name.indexOf(this.input_value) == -1
                    })
                ) {
                    this.input_value = ''
                    return alert('No such product')
                }
                this.shopPings = this.shopPings.filter((v) => {
                    v.name.replace(this.input_value, this.input_value)
                    return v.name.indexOf(this.input_value) != -1
                })
            }

Full code:

<template>
    <div class="shopCar">
        <header>

            <button type="button" @click="delSelect">Batch delete</button>
            <button type="button" @click="alldel">Clear shopping cart</button>
            <button type="button" @click="xian">Add</button>
            <button type="button" @click="jiang">Sort</button>
            <input type="text" placeholder="Please enter the name of the product you want to search" v-model="input_value" @keyup.13="search">
            <div class="xiu" v-show="dis1">
                <input type="text" placeholder="Name" v-model="name">
                <input type="text" placeholder="Price" v-model="price">
                <input type="text" placeholder="Quantity" v-model="count">
                <input type="text" placeholder="Origin" v-model="county">

                <button type="button" @click="xiugai">Confirm changes</button>
            </div>
            <div class="add" v-show="dis">
                <input type="text" placeholder="Name" v-model="name">
                <input type="text" placeholder="Price" v-model="price">
                <input type="text" placeholder="Quantity" v-model="count">
                <input type="text" placeholder="Origin" v-model="county">

                <button type="button" @click="tian">Confirm to add</button>
            </div>
        </header>
        <main>
            <ul>
                <li>
                    <p><input type="checkbox" v-model="allChecked">
                        Select All</p>
                    <p>Name</p>
                    <p>Origin</p>
                    <p>Quantity</p>
                    <p>Unit price</p>
                    <p>Subtotal</p>
                    <p>Operation</p>
                </li>
                <li v-for="(item,index) in shopPings" :key="index">
                    <p><input type="checkbox" v-model="item.checked">{{item.id}}</p>
                    <p>{{item.name}}</p>
                    <p>{{item.counrty}}</p>
                    <p><button type="button" @click="add(item)">+</button>
                        <input type="text" v-model="item.count" style="width:20px">
                        <button type="button" @click="remove(item)">-</button>
                    </p>
                    <p>{{item.price}}</p>
                    <p>{{item.price*item.count |suffix}}</p>
                    <p>
                        <button type="button" @click="xiu(index)"> Modify</button>

                        <button @click="del(index)">Delete</button>
                    </p>
                </li>
            </ul>
        </main>
        <footer>
            <p>Total {{state.sum |suffix}}</p>
        </footer>
    </div>
</template>
<style scoped lang="scss">
    .shopCar {
        width: 1000px;
        border: 2px solid black;
        margin: 100px auto;
        overflow:auto;

        header {
            display: flex;
            justify-content: space-between;
            width: 600px;
            height: 27px;
            overflow: hidden;

            .add {
                width: 400px;
                background: #e4e1e1;
                position: absolute;
                left: 39%;
                top: 40%;

                input {
                    display: block;
                    margin: 20px auto;

                }

                button {
                    display: block;
                    margin: 0 auto;
                }
            }

            .xiu {
                width: 400px;
                background: #e4e1e1;
                position: absolute;
                left: 39%;
                top: 40%;

                input {
                    display: block;
                    margin: 20px auto;

                }

                button {
                    display: block;
                    margin: 0 auto;
                }
            }
        }

        main {
            // height: 400px;
            margin-top: 10px;

            ul {

                li {
                    height: 78px;
                    border-bottom: 2px solid black;
                    display: flex;
                    justify-content: space-between;

                    p {
                        float: left;
                        width: 140px;
                        height: 27px;
                        border: 2px solid black;
                        text-align: center;
                    }
                }
            }
        }

        footer {
            height: 50px;
            margin-top: 13px;
            line-height: 50px;
        }
    }
</style>
<script>
    const shopData = [{
            id: "",
            name: "shoes",
            counrty: "Shanxi",
            count: 1,
            price: 800,
        },
        {
            id: "",
            name: "Cabinet",
            counrty: "Beijing",
            count: 1,
            price: 3200,
        },
        {
            id: "",
            name: "Lipstick",
            counrty: "Hebei",
            count: 2,
            price: 200,
        },
        {
            id: "",
            name: "Hamburger",
            counrty: "Henan",
            count: 2,
            price: 200,

        },

    ]

    export default {
        //Filters: {
            suffix(value) {
                let price = Number(value)
                return `¥${price.toFixed(2)}`
                //Insert a ¥ symbol before the amount and define the decimal point as two digits}
        },
        computed: {

            //Select all allChecked: {
                get() {
                    const checkeds = this.shopPings.filter((item) => item.checked)
                    return checkeds.length === this.shopPings.length
                },
                set(state) {
                    // console.log(state)
                    this.shopPings.map((item) => {
                        item.checked = state
                        return item
                    })
                }
            },
            //Subtotal calculation totalPrice: function () {
                var total = 0;
                for (var i = 0; i < this.checkList.length; i++) {
                    var item = this.checkList[i];
                    total += item.price * item.count;
                }
                return total.toLocaleString();
            },
            //Calculate the total price of the selected item state() {
                const checkeds = this.shopPings.filter((item) => item.checked)
                const checked = checkeds.length === this.shopPings.length
                const sum = checkeds.reduce((a, b) => {
                    return a + b.count * b.price;
                }, 0)
                return {
                    count: checkeds.length,
                    sum
                }
            },
        },
        data() {
            return {
                shopPings: [],
                dis: false, //Confirm submission dis1: false, //Confirm modification id: "",
                name: "", //name price: "", //unit price count: "", //quantity counrty: "", //origin input_value: "", //value entered in the query box}
        },
        mounted() {
            window.fetch("/").then(() => {
                this.shopPings = shopData.map((item) => {
                    item.checked = false
                    return item
                })
            })
        },
        methods: {
            //Add product xian() {
                if (!this.dis == false) {
                    this.dis = false
                } else {
                    this.dis = true
                }
            },
            //Confirm adding tian() {
                if (this.name == "" || this.county == "" || this.price == "") {
                    alert("Product information cannot be empty!")
                    return false
                } else {

                    this.shopPings.push({
                        name: this.name,
                        counrty: this.counrty,
                        price: this.price,
                        count: this.count,
                    })
                }
                this.name = "",
                    this.counrty = "",
                    this.price = "",
                    this.count = ""
                this.dis = false
            },

            //Delete product del(index) {
                this.shopPings.splice(index, 1);
            },

            //Delete the selected item delSelect() {
                this.shopPings = this.shopPings.filter((item) => {
                    if (!item.checked) {
                        return item
                    }
                })
            },
            //delete all alldel() {
                this.shopPings = []
            },
            //Reduce purchase remove(data) {
                if (data.count > 0) {
                    data.count--
                }
                if (data.count === 0) {
                    data.checked = false
                }
            },
            //Add purchase add(data) {
                data.count++
            },
            //Modify product xiu(i) {
                this.int = i
                if (!this.dis1 == false) {
                    this.dis1 = false
                } else {
                    this.dis1 = true
                }
            },
            // Confirm the modification xiugai() {
                console.log(this.int)
                let index = this.int
                console.log(this.name, this.price, this.count, )
                this.shopPings[index].name = this.name
                this.shopPings[index].price = this.price
                this.shopPings[index].county = this.county
                this.shopPings[index].count = this.count

                this.dis1 = false
            },
            //Descending orderjiang() {
                this.shopPings.sort((a, b) => {
                    // Sort based on data return a.price - b.price;
                })
            },
            search() {
                if (!this.input_value) {
                    return alert('Please enter content')
                }
                if (
                    this.shopPings.every((v) => {
                        v.name.indexOf(this.input_value) == -1
                    })
                ) {
                    this.input_value = ''
                    return alert('No such product')
                }
                this.shopPings = this.shopPings.filter((v) => {
                    v.name.replace(this.input_value, this.input_value)
                    return v.name.indexOf(this.input_value) != -1
                })
            }

        }
    }
</script>

Summarize

This is the end of this article about how to use vue to implement all the functions of a shopping cart. For more information about how to use vue to implement shopping cart functions, please search previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Implementing shopping cart function based on Vuejs
  • Vue implements shopping cart function
  • Vue realizes the shopping cart function of the mall
  • Simple shopping cart function example implemented by vuex
  • vue+vant-UI framework realizes the checkbox selection and deselection function of the shopping cart
  • Detailed explanation of the shopping cart function implemented by Vue.js
  • Vuejs implements shopping cart function
  • Detailed explanation of Taobao shopping cart function implemented by Vue
  • Vue.js implements simple shopping cart function
  • Detailed explanation of how to develop shopping cart function with Vue.js

<<:  mysql installer community 8.0.16.0 installation and configuration graphic tutorial

>>:  How to run .sh files in Linux system

Recommend

Vue storage contains a solution for Boolean values

Vue stores storage with Boolean values I encounte...

mysql installer community 8.0.12.0 installation graphic tutorial

This tutorial shares the installation of mysql in...

11 common CSS tips and experience collection

1. How do I remove the blank space of a few pixels...

Detailed explanation of MySql slow query analysis and opening slow query log

I have also been researching MySQL performance op...

960 Grid System Basic Principles and Usage

Of course, there are many people who hold the oppo...

Docker enables seamless calling of shell commands between container and host

As shown below: nsenter -t 1 -m -u -n -i sh -c &q...

The image element img has extra blank space in IE6

When doing DIV+CSS layout of the page, it is very...

Vue implements automatic jump to login page when token expires

The project was tested these days, and the tester...

Explanation of Truncate Table usage

TRUNCATE TABLE Deletes all rows in a table withou...

CSS inheritance method

Given a div with the following background image: ...

10 very good CSS skills collection and sharing

Here, clever use of CSS techniques allows you to g...

Solution for Nginx installation without generating sbin directory

Error description: 1. After installing Nginx (1.1...

What should I do if I want to cancel an incorrect MySQL command?

I typed a wrong mysql command and want to cancel ...

Detailed introduction to deploying k8s cluster on centos7 system

Table of contents 1 Version and planning 1.1 Vers...

Problems and solutions when installing and using VMware

The virtual machine is in use or cannot be connec...