I am working on a component that has a list of objects and I need to implement functionality where, when toggled, the objects' title
prop is either added to or removed from an array. Adding the value was easy to do, but removing it has proven challenging because the items can be selected and pushed onto the array in any order:
data
data () {
return {
options = [
{
title: "cookies",
isSelected: false
},
{
title: "cakes",
isSelected: false
},
{
title: "brownies",
isSelected: false
}
],
selected : []
}
},
template
<template>
<div>
<div
v-for="(item, index) in options"
:key="index"
v-on:click="toggleSelected(index, item)">
{{ item.title }}
</div>
</div>
</template>
script
toggleSelected: function (index, item) {
item.isSelected = !item.isSelected
if (this.selected.includes(item.title)) {
return this.selected.splice(item.title) // trying to remove item.title, but not working as expected
}
return this.selected.push(item.title)
}
I realize my use of splice
might be incorrect, so I'm seeking advice on how to achieve the desired outcome, with or without using splice
.