我有基本的v-循环播放array:
<template v-for="(item, index) in array">
{{item.text}}
<btn @click="delete">Delete me!</btn>
</temaplate>
Run Code Online (Sandbox Code Playgroud)
我希望能够删除循环中的项目。我该怎么做?我可以简单地使用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)
}
}
}
})Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1407 次 |
| 最近记录: |