繁体   English   中英

在Vue中按值拼接数组?

[英]splice array by value in Vue?

我在组件中有一个对象列表,想要添加功能,当切换时,可以将它们的title属性推入数组或删除。 我的推入部分很容易实现,但是删除值非常困难,因为按索引进行拼接在这种情况下无济于事,因为可以按任意顺序选择项目并将其推入数组:

数据

data () {
    return {
        options = [
            {
                title: "pie",
                isSelected: false
            },
            {
                title: "cupcakes",
                isSelected: false
            },
            {
                title: "muffins",
                isSelected: false
            }
        ],
        selected : []
    }
},

模板

<template>
    <div>
        <div
            v-for="(item, index) in options"
            :key="index"
            v-on:click="toggleSelected(index, item)">
            {{ item.title }}
        </div>
    </div>
</template>

脚本

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)
}

我知道我在语法上错误地使用了splice ,那么我如何实现我想要做的事情? 有无splice

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

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

splice功能的预期参数是开始索引删除计数

这意味着您必须执行以下操作:

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

拼接的正确形式是(index, count, insert) 最后一个参数insert更改要添加到数组的函数的行为,而不是删除。 要在此处使用拼接,您首先必须获取该项目的索引,然后通过省略最后一个参数来指定要删除一个项目。

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

另外, filter可以作为一种简单的替代方法,这是我在这里使用的方法。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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