M
M
Mikhail Smirnov2018-07-03 18:54:06
Vue.js
Mikhail Smirnov, 2018-07-03 18:54:06

How to synchronize product and cart in vue.js?

Good afternoon!
How to do it right to add a product to an order, you could then find it there
. For example, if there is no product in the order, then just add it to the order, if it is already there, then increase its quantity in the basket by 1, and in property of the goods to reduce by 1 quantity in stock.
code example:

<script>
    import axios from 'axios'
    export default {
        data() {
            return {
                products: [],
                orderList: [],
                loader: false,
            }
        },
        mounted: function () {
            this.$nextTick(function () {

                axios.post('/api/get-products', {

                })
                    .then(response => {
                        this.products = response.data.products
                    })
                    .catch(error => {
              
                    })

            })
        },
        methods: {
            addToOrder: function(product) {
                    this.orderList.push({
                        product: product,
                        quantity: 1
                    });
            },
        },
        watch: {

        },
    }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Boltnev, 2018-09-01
@AntonBoltnev

create a condition: if the orderList array has an element with id="milk"(id of your product) , then push the array, forming a product object in it (quantity, name, price, etc.). To do this, you can use the method: if orderList.find(i => i.id != “milk”) , then push(). If there is such an id, then you look for this object, look for the number in it and increase ++ by 1. That's it :)
Option 2: cut vuex. Create props [amount] in the order component. Bind props to the appropriate vuex store element. And on the button to increase the number, hang $emit, which would increase the value of store by 1 on click. You will automatically tick the number of goods in the basket when you change the store.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question