简体   繁体   中英

splice array by value in Vue?

I have a list of objects in my component and want to add functionality that when toggled, either get their title prop pushed onto an array or removed. The push part i implemented rather easily, however removing the value is pretty difficult since splicing by index doesn't help in this situation being that the items can be selected and pushed onto the array in any order:

data

data () {
    return {
        options = [
            {
                title: "pie",
                isSelected: false
            },
            {
                title: "cupcakes",
                isSelected: false
            },
            {
                title: "muffins",
                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) // does not work as expected
    }
    return this.selected.push(item.title)
}

I know i am syntactically using splice incorrectly, so how do i achieve what i am looking to do? with or without splice ?

为什么不简单地将其过滤掉呢?

return this.selected = this.selected.filter(title => title !== item.title);

The expected parameters of the splice function are the start index and the delete count

Which means that you'll have to do something like this:

this.selected.splice(this.selected.indexOf(item.title), 1);

The correct form for splice is (index, count, insert) . The last parameter insert changes the behavior of the function to add to the array, as opposed to removing. To use splice here, you'll first have to get the index of the item, then specify that you want to remove one item by leaving the last parameter out.

const index = this.selected.indexOf(item.title)
if (index > -1) {
  this.selected.splice(index, 1);
}

Alternatively, filter works as a simple alternative, and is the approach I'd go with here.

this.selected = this.selected.filter(title => title !== item.title)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM