how to alterate state in array object at v-for loop?

84 views Asked by At

im making a inventory system at Vue Js using Nuxt. im trying to make a function that find in the invendory and if the item exist in the inventory the quantity increase in one. The problem? the function is runs successfully but i can not see changes in my V-for list but if im push other object in my array the v-for loop is updated whit the new data.

<script lang="js">
    import Vue from 'vue'
    import Navbar from '../../components/Navbar'
    export default Vue.extend({
        components: {
            Navbar
        },
        data(){
            return{
                products: [
                    { name: 'abrazadera', id: 0, image: "https://carritoferretero.com/wp-content/uploads/2018/05/products-abrazadera-de-arranque-carrito-ferretero_2.png", price: 20},
                    { name: 'tuerca', id: 1, image: "https://cdn.homedepot.com.mx/productos/819576/819576-d.jpg", price: 40},
                    { name: 'martillo', id: 2, image: "https://cdn.homedepot.com.mx/productos/680442/680442-d.jpg", price: 50}
                ],
                venta: [

                ]
            }
        },
        methods: {
            addProduct(id, index){
                let busqueda = this.venta.find( item => item.id == id)
                console.log(busqueda)
                if(typeof(busqueda) == 'undefined'){
                    let newObj = this.products[index]
                    newObj.cantidad = 1
                    this.venta.push(newObj)
                } else {
                    busqueda = this.venta.findIndex( element  => element.id == id )
                    let newObj = this.venta[busqueda]
                    newObj.cantidad = this.venta[busqueda].cantidad + 1
                    this.venta[busqueda] = newObj
                }
            }
        }
    })
</script>

in my "addProduct" function im find a product in my "venta" inventory if item does not exist im add a product in my inventory else im add + 1 quantity. the function is working correctly but the rendering vfor does not is updating. The v-for list is updating only if im add a new element using "arrayelement.push"

any idea for solve this? thanks for the answers

1

There are 1 answers

0
kdau On BEST ANSWER

Vue 2 can't detect changes to existing items in an array when made the usual way; here's the full explanation. You'll need to change this line:

this.venta[busqueda] = newObj

to:

this.venta.splice(busqueda, 1, newObj)

(You can also use Vue.set, but splice is at least still a standard array operation.)