I have an array of objects like this:
daySelected: [
{
selectDay: day,
time: [
{
defaulTimeStart: "08:00",
defaultTimeEnd: "00:00",
}
]
},
{
selectDay: day,
time: [
{
defaulTimeStart: "08:00",
defaultTimeEnd: "00:00",
}
]
},
//etc....
];
the array is formed with this function which pushes an object on click:
const object = {
selectDay: day,
time: [
{
defaulTimeStart: "08:00",
defaultTimeEnd: "00:00",
},
],
};
this.daySelected.push (object);
so far it works... the problem arises when I want to delete the current pushed element:
this.daySelected.splice(this.daySelected.indexOf(object), 1);
if I click on the element at the end of the array to delete it it works, but if I click on a middle element or at the beginning of the array, it deletes the next one...
Rather than indicate the index by this.daySelected.indexOf(object)
, try to indicate directly from the v-for
.
You maybe iterate the daySelected
array using v-for
as follows:
<div v-for="(obj, index) in daySelected">
...
// use `index` to pass as a parameter of the `splice` method.
... deleteObj(index) ...
...
</div>
<script>
...
methods: {
deleteObj(index) {
this.daySelected.splice(index, 1);
}
}
...
</script>