Vue does not correctly remove item from vfor

I have this custom component in vue callled "dm-vehicle-spec"

 <dm-vehicle-spec @_handleRemoveSpec="_handleRemoveSpec" v-for="spec, index in vehicleSpecs" :key="index" :index="index" :spec="spec"></dm-vehicle-spec>

which looks like the following

<script>

export default {
    props: ["spec"],

    data() {
        return {
            specName: null,
            specValue: null,
        }
    },

    mounted() {
        if (this.spec.detail_name && this.spec.detail_value) {
            this.specName = this.spec.detail_name;
            this.specValue = this.spec.detail_value;
        }
    },  

    computed: {
        getSpecNameInputName() {
            return `spec_${this.spec.id}_name`;
        },

        getSpecValueInputName() {
            return `spec_${this.spec.id}_value`;
        },
    },

    methods: {
        _handleRemoveSpec() {
            this.$emit("_handleRemoveSpec", this.spec.id);
        }
    },
}

</script>

<template>
    <div class="specs-row flex gap-2 w-full items-center">
        <div class="col-1 w-5/12">
            <input placeholder="Naam" type="text" :id="getSpecNameInputName" class="w-full h-12 spec_name rounded-lg border-2 border-primary pl-2" v-model="specName">
        </div>
        <div class="col-2 w-5/12">
            <input placeholder="Waarde" type="text" :id="getSpecValueInputName" class="w-full h-12 spec_name rounded-lg border-2 border-primary pl-2" v-model="specValue">
        </div>
        <div @click="_handleRemoveSpec" class="col-3 w-2/12 flex items-center justify-center">
            <i class="fas fa-trash text-lg"></i>
        </div>
    </div>
</template>

so when i have 3 specs, 1 from the database and 2 customs i have the following array vehicleSpecs (Which i loop over)

[
   {"id":23,"vehicle_id":"1","detail_name":"Type","detail_value":"Snel","created_at":"2022-11-07T19:06:26.000000Z","updated_at":"2022-11-07T19:06:26.000000Z","deleted_at":null}, 
   {"id":24},
   {"id":25}
]

enter image description here

so lets say i want to remove the second item from the list so the one with test1 as values, then the array looks like

[{"id":23,"vehicle_id":"1","detail_name":"Type","detail_value":"Snel","created_at":"2022-11-07T19:06:26.000000Z","updated_at":"2022-11-07T19:06:26.000000Z","deleted_at":null},{"id":25}]

So the second array item is removed and thats correct because object with id 24 no longer exsist but my html shows

enter image description here

that the value for object with id 24 still exists but the value for object with id 25 is removed, how is that possible?

If u need any more code or explaination, let me know

Any help or suggestions are welcome!

>Solution :

Index is not a good choice to use as v-for key.
Indexes are changing when you delete something from array.
Try using another property as a key.

Leave a Reply