gpt4 book ai didi

javascript - vuejs - 如何删除 v-for 项目中的数组项目。元素?

转载 作者:搜寻专家 更新时间:2023-10-30 22:31:49 24 4
gpt4 key购买 nike

我有基本的 v-for,它在 array 上循环:

<template v-for="(item, index) in array">
{{item.text}}
<btn @click="delete">Delete me!</btn>
</temaplate>

我希望能够在我的循环中删除一个项目。我该怎么做?我可以简单地使用 splice() 或删除没有我要删除的元素的索引吗?

最佳答案

使用Array.splice() .

app = new Vue({
el: "#app",
data: {
items: [{'text':'a'},{'text':'b'}]
},
methods: {
deleteItem: function (item, index) {
if(this.items[index] === item) {
// The template passes index as the second parameter to avoid indexOf,
// it will be better for the performance especially for one large array
// (because indexOf actually loop the array to do the match)
this.items.splice(index, 1)
} else {
let found = this.items.indexOf(item)
this.items.splice(found, 1)
}
}
}
})
<script src="https://unpkg.com/vue@2.5.16/dist/vue.js"></script>
<div id="app">
<template v-for="(item, index) in items">
{{item.text}}
<button @click="deleteItem(item, index)">Delete me!</button>
</template>
</div>

关于javascript - vuejs - 如何删除 v-for 项目中的数组项目。元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50140910/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com